In Java, super.getClass () prints "Child" and not "Parent" - why?

In Java classes and objects, we use the keyword "this" to refer to the current object within the class. In a sense, I believe that "this" actually returns an object on its own.

An example for this:

class Lion
{
    public void Test()
    {
        System.out.println(this);  //prints itself (A Lion object)
    }
}

In a superclass and subclass scenario. I thought the keyword "super" would return a superclass object. However, it seems that this time I was mistaken:

Example:

class Parent
{
    public Parent(){
    }
}

class Child extends Parent
{
    public Child(){
        System.out.println(super.getClass()); //returns Child. Why?
    }
}

My Quesiton: In the above example, I expected the compiler to print class Parent, however it outputs class Child. Why is this so? What really brings super?

+4
source share
3 answers

super . :

class Parent {
    @Override public String toString() {
        return "Parent";
    }
}

class Child extends Parent {
    @Override public String toString() {
        return "Child";
    }

    public void callToString() {
        System.out.println(toString()); // "Child"
        System.out.println(super.toString()); // "Parent"
    }
}

getClass(), , , , , , , , , , Parent.class, , , Child. ( , API Class.)

. :

@Override public void validate() {
    // Allow the parent class to validate first...
    super.validate();
    // ... then perform child-specific validation
    if (someChildField == 0) {
        throw new SomeValidationException("...");
    }
}
+11

getClass() . . , , , , , , getClass() , .

Super , , , .

+2

The super keyword will invoke the overridden method in the parent. The child did not override this method. Therefore, he will return the correct class, which is the Child. This way you are not getting an instance of the Parent class.

0
source

All Articles