views:

196

answers:

4

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?

+11  A: 

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.

Bozho
+1 for beating me.
The Elite Gentleman
A note on using polymorphism in this situation: You could have a method `getType()` or something similar in the implementation of `A` and override that method in `B` and `C`. Since all methods are virtual in java, a call to `getType()` would resolve the specific subtype.
aioobe
+3  A: 

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.
The Elite Gentleman
+2  A: 

Short answer to your question

Is there a way to find out the derived class's name from a base class object?

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's getClass() method.

Tim Drisdelle
A: 

There 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

harigm