以下代码中的 super 指向什么?

What is super pointing to in the following code?

下面代码中第4行的super指向什么地址?

public class SuperChk {
    private void test() {
        System.out.println(toString());
        System.out.println(super.toString()); //4
    }

    @Override
    public String toString() {
        return "Hello world";
    }

    public static void main(String[] args) {
        SuperChk sc1 = new SuperChk();
        sc1.test();
    }
}
Java中的

类全部派生自Object。由于您没有明确的父项 class,因此父项是 Object,而 super 引用 ObjectObject does support the toString() method. See the Java class hierarchy.

这样看。

隐含地,您的 class 将从超级 class 对象继承,因此您可以使用 Object 引用或 SuperChk 引用访问您的对象

对象

public class Object {
    // Other methods

    public String toString(){
        // This is the method super.toString() will use once called in SuperChk
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

}

SuperChk

public class SuperChk extends Object {
    private void test() {
        System.out.println(toString());
        System.out.println(super.toString()); //4
    }

    @Override
    public String toString() {
        return "Hello world";
    }

    public static void main(String[] args) {
        SuperChk sc1 = new SuperChk();
        sc1.test();
    }
}

输出

Hello world
SuperChk@15db9742

您可以看到对象 class 中的 toString() 方法打印:

  • class名字在前。
  • 然后“@”
  • 然后是HashCode的十六进制表示也定义在superclass的一个方法中Object

super 不是表达式。所以 super 不会 "point to" 任何东西,你不能单独使用 super

super.something() 是一个表达式,它允许您在 this 指向的对象上调用方法,但是查找要调用的实现是从 superclass这是 class 的代码,而不是从对象的运行时 class 开始,如果您这样做 this.something().

这里,toString()super.toString() 都在 this 指向的对象(这是一个 SuperChk 实例)上被调用。但是,它们调用了不同的 toString() 实现——在第一种情况下,查找基于对象的运行时 class,即 SuperChk,而 SuperChk 确实提供了它自己实现了 toString(),因此使用了 SuperChk 的实现。在第二种情况下,查找基于class,即代码在(SuperChk)中的class的superclass,即Object,因此使用 ObjecttoString()