Super. getClass () trap

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.