考虑以下两种情况
案例一
我有一个简单的 Java 类,它有一个无参数构造函数。下面是代码
public class TestClassOne {
public TestClassOne() {
System.out.println("Parent class of TestClassOne is :" + this.getClass().getSuperclass());
}
}
Object 是所有 Java 类的父类(super class)。因此,当我在主方法中创建 TestClassOne 的对象并运行它时,它给出了期望输出,即
Parent class of TestClassOne is :class java.lang.Object
案例二
现在我有另一个类,名为 TestClassTwo,它扩展了 TestClassOne。下面是代码
public class TestClassTwo extends TestClassOne {
}
现在,当我在主方法中创建 TestClassTwo 对象并运行它时,TestClassOne 的无参数构造函数也会被隐式调用,因为 TestClassOne 是 TestClassTwo 的父类(super class) 并在控制台中打印输出。我原以为输出会与情况 I 相同,但事实并非如此。输出是
Parent class of TestClassOne is :class org.test.TestClassOne
为什么上面的输出与案例一不一样?
有人可以解释一下为什么案例一和案例二的输出不同吗?
最佳答案
您正在对 this
调用 getClass()
。输出不同,因为:
- 在情况 1 中,
this
引用TestClassOne
的实例。 - 在情况 2 中,
this
引用TestClassTwo
的实例。
关于java - 意外输出 "this.getClass().getSuperclass()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30217814/