In Java, is it safe to assume that getClass() called inside a constructor of a class used as a base class will provide information about the derived class, rather than the class of the base class?
It seems to work, but I guess that doesn’t necessarily mean it’s safe.
For example, if I have the following two classes:
public class Parent {
public Parent() {
System.out.println(getClass().getName());
}
}
And:
public class Derived extends Parent {
public Derived() {
super();
}
public static void main(String... args) {
new Derived();
}
}
When I run the main() method in the Derived class it prints: Derived (which is what I was hoping). But can I rely on that behavior across JVMs?
getClassis one ofObject‘s methods and returns the runtime class ofthis:So yes, it will always return
Derived.