Consider the inheritance hierarchy in the diagram below:
A collection, such as ArrayList may be of a general type..
For instance:
ArrayList<Superclass> list = new ArrayList<Superclass>();
All objects of Superclass type may be added to the list.
For instance:
add(new Superclass());
add(new SubClassWhite());
add(new SubClassBlack());
add(new SubClassA());
add(new SubClassB());
add(new SubClassX());
add(new SubClassY());
The list now contains 7 objects, all of type Superclass. Even though many of the objects are specialisations of Superclass, they all have the context of Superclass.. This means we can only use each object as the general type (Superclass), regardless of its specialisation.
Getting the specific type of an object
If we want to discover the actual run time type of each object in the list, we call the getClass() method. This method is inherited by all objects from the Object class and returns the run time class of the object.
The equals() method (also inherited from Object) performs an equality check on the current object in the list, with the class name we are looking for.
if (list.get(6).getClass().equals(SubClassWhite.class) {
//
}
If this expression evaluates to true, we are then able to cast the general object type into it’s specialised type:
SubClassWhite s = (SubClassWhite)list.get(6);
The object called s is now of type SubClassWhite and may be used in the context.
Full code listing (including a loop to iterate through the list) which finds objects in the list with the run time type of SubClassWhite and casts it accordingly.:
ArrayList<Superclass> list = new ArrayList<Superclass>();
add(new Superclass());
add(new SubClassWhite());
add(new SubClassBlack());
add(new SubClassA());
add(new SubClassB());
add(new SubClassX());
add(new SubClassY());
for (int x = 0; x < list.size(); x ++) {
if (list.get(x).getClass().equals(SubClassWhite.class) {
SubClassWhite s = (SubClassWhite)list.get(x);
}
}
Getting the general type of an object
If we want to find all instances of SubClassWhite (remember that SubClassWhite is a subclass of Superclass but also a superclass itself) we use the instanceof operator. Using this method, all instances of SubClassWhite, SubClassX and SubClassY will be discovered.
for (int x = 0; x < list.size(); x ++) {
if (list.get(x) instanceof SubClassWhite.class) {
SubClassWhite s = (SubClassWhite)list.get(x);
}
}






