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?
getClass() is the method of Object class. This method returns the runtime class of this object. The class object which is returned is the object that is locked by static synchronized method of the represented class.
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category.
java. lang. Object class is the super base class of all Java classes. Every other Java classes descends from Object.
getClass
is one of Object
's methods and returns the runtime class of this
:
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
So yes, it will always return Derived
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With