Super. getClass method call for Java interview questions

Source: Internet
Author: User

The super. getClass method of Java interview questions is called. Today, I read a Java interview question from the Internet, and the result fell into the trap. I think this interview question is quite good, so I will share it with you! Let's take a look at the code of the program to see what the final output result is?

Import java. util. date; public class Test extends Date {public void test () {System. out. println (super. getClass (). getName ();} public static void main (String [] args) {new Test (). test ();}}

 

If you do not understand it, you are likely to get the wrong answer. In fact, the answer is Test. Is it strange? The result is Test. This question belongs to the question of sharp brain turns. It is very simple and easy to fall into the trap. I think most people may fall into the trap because this class inherits. If you call getClass () directly in the test method (). getName () method is equivalent to calling this. getClass (). getName (), and the returned result is the name of the Test class. Because getClass () is defined as final in the Object class and the subclass cannot overwrite this method, the Date class does not have this method, call getClass () 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: getClass (). getSuperClass (). getName ();

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.