First, let's give a question. What is the output result of the following program?
Java code
Import java. util. Date;
Public class Test extends Date {
Public static void main (String [] args ){
New Test (). test ();
}
Public void test (){
System. out. println (super. getClass (). getName ());
}
}
Import java. util. Date;
Public class Test extends Date {
Public static void main (String [] args ){
New Test (). test ();
}
Public void test (){
System. out. println (super. getClass (). getName ());
}
}
You may think it is Date, but the actual result is Test. Yes, you are not mistaken. super. getClass () does not return a reference to the superclass. Let's do another experiment. In the test method, call the getClass (). getName () method directly, and Test is returned. Why didn't super work? In short, super does not represent a reference of a super class.
Super does not represent a reference capability of a superclass, but rather calls the method of the parent class. Therefore, in the subclass method, System. out. println (super) cannot be used; or super. super. mathod ();
In fact, super. getClass () indicates the method to call the parent class. The getClass method comes from the Object class, which returns the type of the Object at runtime. Because the object type at runtime is Test, this. getClass () and super. getClass () both return Test.
In addition, because getClass () is defined as final in the Object class and the subclass cannot overwrite this method, getClass () is called in the test method (). the getName () method is actually calling the getClass () method inherited from the parent class, which is equivalent to calling super. getClass (). getName () method, so, super. getClass (). the getName () method also returns Test.
If you want to get the name of the parent class, use the following code:
Java code
GetClass (). getSuperClass (). getName ();
This article is from "erli"