super 不是应该引用未在此处创建的 Object 类类型的对象吗?
public class SuperChk
{
void test()
{
System.out.println(super.toString());
}
public static void main(String[] args)
{
SuperChk sc1 = new SuperChk();
System.out.println(sc1);
sc1.test();
}
}
最佳答案
Isn't super suppose to refer object of Object class type which is not created here?
呃……不。
super
关键字(以这种方式使用时)表示“想要引用 this
,但将其视为其父类(super class)的实例”。这是子类调用父类(super class)中可能已覆盖的方法的方式。
java.lang.Object
类是所有引用类型的最终父类(super class),您的 SuperChk
类也不异常(exception)。您的 SuperChk 类具有 toString() 方法(继承自 Object)并且 super.toString() 正在调用它.
现在,在您的示例中,super.
是多余的,因为 SuperChk
不会覆盖 String。但这里有一个例子,它并不多余......
public class SuperChk {
private void test() {
System.out.println(toString());
System.out.println(super.toString());
}
@Override
public String toString() {
return "Hello world";
}
public static void main(String[] args) {
SuperChk sc1 = new SuperChk();
sc1.test();
}
}
如果您编译并运行它,您将看到 toString()
和 super.toString()
正在调用不同的方法。
关于java - 为什么这里的 super 引用的地址与引用变量 sc1 引用的地址相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314578/