Is there a way to find out the name of derived class from a base class instance?
e.g.:
class A{
....
}
class B extends A{
...
}
class c extends A{
...
}
now if a method returns an object of A
, can I find out if it is of type B
or C
?
The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).
Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False. Parameters: Object: class to be checked.
The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.
using either instanceof
or Class#getClass()
A returned = getA();
if (returned instanceof B) { .. }
else if (returned instanceof C) { .. }
getClass()
would return either of: A.class
, B.class
, C.class
Inside the if-clause you'd need to downcast - i.e.
((B) returned).doSomethingSpecificToB();
That said, sometimes it is considered that using instanceof
or getClass()
is a bad practice. You should use polymorphism to try to avoid the need to check for the concrete subclass, but I can't tell you more with the information given.
Have you tried using instanceof
e.g.
Class A aDerived= something.getSomethingDerivedFromClassA();
if (aDerived instanceof B) {
} else if (aDerived instanceof C) {
}
//Use type-casting where necessary in the if-then statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With