[英]Unexpected output of “this.getClass().getSuperclass()”
Consider below two cases 考虑以下两种情况
I have a simple Java class which has a no-arguments constructor. 我有一个简单的Java类,它具有无参数的构造函数。 Below is the code
下面是代码
public class TestClassOne {
public TestClassOne() {
System.out.println("Parent class of TestClassOne is :" + this.getClass().getSuperclass());
}
}
Object is the super class of all Java classes. 对象是所有Java类的超类。 So when I am creating an object of TestClassOne in my main method and run it, it is giving me the desire output which is
因此,当我在主要方法中创建TestClassOne的对象并运行它时,它为我提供了所需的输出 ,即
Parent class of TestClassOne is :class java.lang.Object
Now I have another class, named as TestClassTwo which extends TestClassOne. 现在,我有另一个名为TestClassTwo的类,它扩展了TestClassOne。 Below is the code
下面是代码
public class TestClassTwo extends TestClassOne {
}
Now when I am creating object of TestClassTwo in my main method and run it, TestClassOne's no-arguments constructor is also getting called implicitly as TestClassOne is super class of TestClassTwo and prints the output in the console. 现在,当我在主方法中创建TestClassTwo的对象并运行它时, 由于TestClassOne是TestClassTwo的超类并在控制台中输出输出,因此TestClassOne的无参数构造函数也被隐式调用 。 I was expecting the output will be same with the case I. But it is not.
我曾期望输出与情况I相同。但是事实并非如此。 The output is
输出是
Parent class of TestClassOne is :class org.test.TestClassOne
Why not the above output is same with Case I ? 为什么以上输出与案例I相同?
Could someone explain me why the outputs are different in Case I and Case II? 有人可以解释一下为什么案例一和案例二的输出不同吗?
You're calling getClass()
on this
. 您正在
this
调用getClass()
。 The output is different because: 输出不同是因为:
this
refers to an instance of TestClassOne
. this
指的是TestClassOne
的实例。 this
refers to an instance of TestClassTwo
. this
指的是TestClassTwo
的实例。 Simple answer: Because this is the superclass. 简单的答案:因为这是超类。
public class TestClassOne {
public TestClassOne() {
System.out.println("Parent class of TestClassOne is :" + this.getClass().getSuperclass());
}
}
This class extends java.lang.Object
(even if it is not explicitly named). 此类
extends java.lang.Object
(即使未显式命名)。
So this
references to an object of the class TestClassOne
and the superclass is java.lang.Object
. 因此,
this
引用了TestClassOne
类的对象,而超类是java.lang.Object
。
public class TestClassTwo extends TestClassOne {
}
This class extends TestClassOne
. 此类
extends TestClassOne
。
So this
references to an object of the class TestClassTwo
and the superclass is TestClassOne
. 因此,
this
引用了TestClassTwo
类的对象,而超类是TestClassOne
。
For this
always the current object is used and never the class where it is defined. 对于
this
总是使用当前对象 ,从来没有在那里它被定义的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.