java - 下面代码中的 super 指向什么?

标签 java variables reference super

以下代码中第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/

相关文章:

java - 从 Aar 模块 Android 执行 Handheld 类中的方法

Java 实例变量与局部变量

python - 如何获取脚本中使用的所有变量和方法名称

php - 使用对不存在值的引用将变量设置为 NULL?

c++ - 在 map 容器中使用映射值重载 << 运算符

c++ - 如果引用类型不匹配,为什么 std::is_constructible 将返回 false?

java - java应用程序中的异常处理

java - 是否有用于 Java 的远程分析器? (最好使用 JMX)

java - Android Studio : 'onCreateViewHolder' method won't recognise my '.xml' layout file from within its class

vue.js - 视觉 : Access Vue component method inside rendered named slot