In Java super.getClass() prints “Child” not “Parent” - why is that?

后端 未结 3 904
[愿得一人]
[愿得一人] 2020-12-07 02:07

In Java classes and objects, we use \"this\" keyword to reference to the current object within the class. In some sense, I believe \"this\" actually returns the object of it

3条回答
  •  既然无缘
    2020-12-07 02:37

    A method call using super just ignores any overrides in the current class. For example:

    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"
        }
    }
    

    In the case of a call to getClass(), that's a method which returns the class it's called on, and can't be overridden - so while I can see why you'd possibly expect it to return Parent.class, it's still using the same implementation as normal, returning Child. (If you actually want the parent class, you should look at the Class API.)

    This is often used as part of an override, in fact. For example:

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

提交回复
热议问题