Reputation: 56199
I have one base class BASE and couple inherited class BASE_1, BASE_2,, BASE_3. I have in code BASE test but how to discover on what class it points: BASE_1, BASE_2 or BASE_3 ?
Upvotes: 0
Views: 46
Reputation: 114767
BASE test = getSomeBase();
// method 1
System.out.println(test.getClass().getName()); // prints the classname
// method 2
if (test instanceof BASE_1) {
// test is a an instance of BASE_1
}
Upvotes: 3
Reputation: 308031
You can use instanceof
to check for a specific type or .getClass()
to get a Class
object describing the specific class:
Base test = getSomeBaseObject();
System.out.println("test is a " + test.getClass().getName());
if (test instanceof Base1) {
System.out.println("test is a Base1");
}
Upvotes: 2
Reputation: 37803
To see the class name of a particular object, you can use:
test.getClass().getName();
But you shouldn't generally care, since any functionality that depends on which subclass you have should be implemented as overridden ("polymorphic") functions in those subclasses.
Upvotes: 3
Reputation: 240900
I am not clear what you are asking but you can make use of getClass()
method and instanceof
operator.
If it is something like
Base b = new Child1();
b.getClass();//will give you child1
Upvotes: 3