There is a keyword in java called instanceof
which compares an instantiated object against a class definition to see if that object is of that specific class type.
In your example you can use the instanceof keyword in your loop, then cast the parent object to a subclass and add it to your list.
for(Parent parent : parentList)
{
if(parent instanceof SubclassA)
{
SubclassA subclass = (SubclassA)parent;
extractMe.add(subclass);
}
}
The casting of parent to subclass (SubclassA)parent
is needed because even though you may have already checked that parent
is of type SubclassA
the compiler still does not know and as such you have to explicitly tell the compiler to cast the parent
object to a SubclassA
.
In addition note that the instanceof
keyword is a built in binary operator in java which will check parent against the class you specify afterwards. parent instanceof SubclassA
will only be true if you can cast parent
to SubclassA
. See the Oracle Docs Example:
The Type Comparison Operator instanceof
The instanceof operator compares an object to a specified type. You
can use it to test if an object is an instance of a class, an instance
of a subclass, or an instance of a class that implements a particular
interface.
The following program, InstanceofDemo, defines a parent class (named
Parent), a simple interface (named MyInterface), and a child class
(named Child) that inherits from the parent and implements the
interface.
class InstanceofDemo {
public static void main(String[] args) {
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: "
+ (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
When using the instanceof operator, keep in mind that null is not an
instance of anything.