以下代码中第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();
}
}
最佳答案
这样看。
隐式地,您的类将从父类(super class) Object 继承,因此您可以使用 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
您可以看到 Object 类中的 toString()
方法打印:
- 首先是类名。
- 然后“@”
- 然后是
HashCode
的十六进制表示形式,它也在父类(super class)Object
的方法中定义
关于java - 下面代码中的 super 指向什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33318426/