Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which class does getClass() report inside a constructor of a base class

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?

like image 984
ᴇʟᴇvᴀтᴇ Avatar asked Sep 28 '12 10:09

ᴇʟᴇvᴀтᴇ


People also ask

What is getClass () in Java?

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.

What is getClass () getName () in Java?

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.

What does class <?> Mean in Java?

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.

What is the base class of all class in Java?

java. lang. Object class is the super base class of all Java classes. Every other Java classes descends from Object.


1 Answers

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.

like image 112
assylias Avatar answered Sep 28 '22 10:09

assylias