Search code examples
javaclassooppolymorphism

How to compare the derived objects from a base class in java?


I have a Base class and two classes are derived from the Base class namely Derived1 and Derived2, I want to check whether object is of type Derived1 or Derived2.

This is my code:

public class Base {
    int ID;
}

public class Derived1 extends Base {
    int subID;
}

public class Derived2 extends Base {
    int subID;
}

public class Program(){
    public static void main(String []args) {
        Base object = new Derived1();

        // I want to check whether "object" is of type Derived1 or Derived2
    }
}


Solution

  • object.getClass() == Derived1.class would return true. As would object instanceof Derived1. object.getClass().getName() would return "com.foo.Derived1". Derived1 = (Derived1) object; would either work, or throw ClassCastException.

    Those are your main 3 options.