Search code examples
javainheritancereturn-type

How to differentiate Sub classes?


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
{
... 
}

Solution

  • if (obj1 instanceof Child1) {
        System.out.println(Child1.class.toString());
    } else if (obj1 instanceof Child2) {
        System.out.println(Child2.class.toString());
    }