Consider below two cases
I have a simple Java class which has a no-arguments constructor. 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. 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
Parent class of TestClassOne is :class java.lang.Object
Now I have another class, named as TestClassTwo which extends 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. I was expecting the output will be same with the case I. But it is not. The output is
Parent class of TestClassOne is :class org.test.TestClassOne
Why not the above output is same with Case I ?
Could someone explain me why the outputs are different in Case I and Case II?
You're calling getClass()
on this
. The output is different because:
this
refers to an instance of TestClassOne
. this
refers to an instance of 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).
So this
references to an object of the class TestClassOne
and the superclass is java.lang.Object
.
public class TestClassTwo extends TestClassOne {
}
This class extends TestClassOne
.
So this
references to an object of the class TestClassTwo
and the superclass is TestClassOne
.
For this
always the current object is used and never the class where it is defined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.