Discover on what inherited class it points
I have one base class BASE and c开发者_如何转开发ouple 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 ?
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
}
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
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.
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");
}
精彩评论