java - 意外输出 "this.getClass().getSuperclass()"

标签 java inheritance superclass

考虑以下两种情况

案例一

我有一个简单的 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/

相关文章:

java & 线程 : interrupted exceptions & how to properly use BlockingQueue's take() method

Java - 将字节转换为字符串并与另一个进行比较

wpf - 有没有更好的方法在 WPF 中继承窗口

perl - 查找 Perl 类的所有父类(super class)的最佳实践是什么?

java - Android 语音识别器自动停止 - 需要像 Google Bolo App 一样实现

java - GWT 在单击异常时不显示根调用跟踪

javascript - JavaScript 中的继承

c# - Swashbuckle 多态性支持问题

java - 编译错误: constructor in class cannot be applied to given types

java - 子类中的构造函数参数