Lets say I have classes SubClass1 and SubClass2 that extend SuperClass. I need to store all of the objects extending SuperClass in a list (List list). Now I pass the list to a function, that can figure out which SubClass the SuperClass was previously. This function should then reconvert the SuperClass back to their respective subclasses. For example,
for (SuperClass superClass : list) {
if (superClass.getType().equals("SubClass1")
SubClass1 subClass = (SubClass1) superClass;
else if (superClass.getType().equals("SubClass2")
SubClass2 subClass = (SubClass2) superClass;
}
This example will result in a class cast exception. Is there any simple solution to get this functionality?
EDIT: As mentioned in one of the answers, this code should cause an exception. Something must be wrong with the getType() method in this example. However, the solution of using the instanceof keyword solves the issue by eliminating the need for a getType() method.
Use the instanceof operator. You could transform you code to: