0

I have Parent class and two subclasses. I want to make a condition in my method checkType(List<Parent>) at my main class whether Parent.getClass() return Child1 or Child2 Let's say i have List that stores all the objects. So the checkType method could count how many child1 and child2 in the List.

abstract class Parent
{
...

   public Parent getClass
   {
     ...
   }

}

class Child1 extends Parent
{
...    
}

class Child2 extends Parent
{
... 
}
Glenio
  • 122
  • 8
  • And where is `checkType` and how do you use it? – lealceldeiro May 18 '19 at 10:47
  • let's say in my main class. I want to compare if it is child1 then return true – Glenio May 18 '19 at 10:48
  • Sorry, it's not clear to me what you're trying to achieve here. I don't see the point for `getClass` return an object of type `Parent`, for what you describe, it should be a string, shouldn't be? If you want to know in Main class what specific type is some instance of `Parent` just use `instanceof` there... but then what's the point of method `getClass` in `Parent` class?. Please, make your question clearer in order to help you better. – lealceldeiro May 18 '19 at 10:52
  • Yes that's what I want to ask about. Thanks – Glenio May 18 '19 at 11:08
  • @lealceldeiro i have edited my question. I know using instanceOf is the answer. I just want to make it clearer to everyone. – Glenio May 19 '19 at 02:02

2 Answers2

1
if (obj1 instanceof Child1) {
    System.out.println(Child1.class.toString());
} else if (obj1 instanceof Child2) {
    System.out.println(Child2.class.toString());
}
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37
0

Create a function checkType() in the parent class. You can override this function in the child class to denote which child class it is. For example,

abstract class Parent {
  public abstract String checkType();
} 
public class Child1 extends Parent {
  public String checkType() {
    return "Child 1"
}
public class Child2 extends Parent {
  public String checkType() {
    return "Child 2"
} 
Chrisvin Jem
  • 3,940
  • 1
  • 8
  • 24
  • Works, but totally not necessary. You can use instanceof to check any reference if it is of a specific class. You are re-inventing the wheel, and badly so. – GhostCat May 18 '19 at 11:31
  • Yea, I didn't think of that initially. And tbh, I have mixed opinions on that, there are cases where I've had to know the "type" of child class without actually knowing all the sub classes in and off themselves. But yes, if the sub classes are known, then that should be the accepted answer. ✌ – Chrisvin Jem May 18 '19 at 11:36
  • @GhostCat also, could you elaborate why you consider this to be 'bad' (aside from it reinventing the wheel)? – Chrisvin Jem May 18 '19 at 11:38