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
?
Have you tried using
instanceof
e.g.
As answered here, you can use this extremely simple approach.
then simply print the current
class
name:Output:
There is no need to store additional
Strings
, checkinstanceof
oroverride
the method in any subclass.You can do it in the subclass' constructor
So
Because it is casted into an "A" object, it will call the "A"
getClassname()
function but will return a value set by the constructor that was the "B" constructor.Note: Call
super();
before setting itThere are 2 ways I can think of 1) One with Using the Java reflection API 2) Other one would be with the instanceOf
Other method can be a Comparing objects to objects, I dont know how it might be, you can try this
Short answer to your question
no, the super-class has no way of telling the name/type of a sub-class.
You have to interrogate the object (which is an instance of a sub-class) and ask if it is an:
instanceof
a particular sub-class, or call it'sgetClass()
method.using either
instanceof
orClass#getClass()
getClass()
would return either of:A.class
,B.class
,C.class
Inside the if-clause you'd need to downcast - i.e.
That said, sometimes it is considered that using
instanceof
orgetClass()
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.