Junior
How can it be determined that a class is derived from another class?
sobes.tech AI
Answer from AI
Using the instanceof operator or the isInstance() method of the Class interface.
// Example with instanceof
if (myObject instanceof MyParentClass) {
// myObject is an instance of MyParentClass or its subclass
}
// Example with isInstance()
if (MyParentClass.class.isInstance(myObject)) {
// myObject is an instance of MyParentClass or its subclass
}
You can also check using the isAssignableFrom() or getSuperclass() methods of the Class class.
// Example with isAssignableFrom()
if (MyParentClass.class.isAssignableFrom(myObject.getClass())) {
// The class of myObject is an instance of MyParentClass or its subclass
}
// Example with getSuperclass() (requires recursive checking)
Class<?> currentClass = myObject.getClass();
while (currentClass != null) {
if (currentClass.equals(MyParentClass.class)) {
// myObject is an instance of MyParentClass or its subclass
break;
}
currentClass = currentClass.getSuperclass();
}
The instanceof operator and the isInstance() method are the most straightforward and recommended for this task. isAssignableFrom() is useful for checking type compatibility during assignment, and getSuperclass() requires additional iterations.