在Java类和对象中,我们使用"this"关键字来引用类中的当前对象.从某种意义上说,我相信"这个"实际上会回归自身的对象.
示例:
class Lion
{
    public void Test()
    {
        System.out.println(this);  //prints itself (A Lion object)
    }
}
在超类和子类的场景中.我认为"超级"关键字会返回超类的对象.但是这次我似乎弄错了:
例:
class Parent
{
    public Parent(){
    }
}
class Child extends Parent
{
    public Child(){
        System.out.println(super.getClass()); //returns Child. Why?
    }
}
我的问题:在上面的例子中,我期待编译器打印出来class Parent,但它打印出来class Child.为什么会这样?什么超级实际返回?
Jon*_*eet 11
使用方法调用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.(如果您确实需要父类,则应该查看ClassAPI.)
事实上,这经常被用作覆盖的一部分.例如:
@Override public void validate() {
    // Allow the parent class to validate first...
    super.validate();
    // ... then perform child-specific validation
    if (someChildField == 0) {
        throw new SomeValidationException("...");
    }
}
| 归档时间: | 
 | 
| 查看次数: | 822 次 | 
| 最近记录: |