Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the subclass from the base class instance?

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?

like image 740
Vaishak Suresh Avatar asked May 18 '10 09:05

Vaishak Suresh


People also ask

How do you find the subclass of an object?

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).

How do you check if a class is a subclass?

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.

How do you find the class name for a subclass?

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.


2 Answers

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.

like image 185
Bozho Avatar answered Oct 11 '22 10:10

Bozho


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.
like image 44
Buhake Sindi Avatar answered Oct 11 '22 09:10

Buhake Sindi