About GetClass () and Super.getclass () in Java

Source: Internet
Author: User

Java code  
Import java.util.date;    
Public  class Test extends date{    &NBSP
    public static void Main (string[] args) {    &NBSP
        new Test (). Test ();    &NBSP
     }   &NBSP
        
     public void Test () {    
         system.out.println (Super.getclass (). GetName ());     
    }    &NBSP
}   

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 might think it's date, but the actual result is test. Yes, you're right, super.getclass () does not return a reference to a superclass. Let's do another experiment, call the GetClass (). GetName () method directly in the test method, and the result returns test. Why super doesn't work. In short, super does not represent a reference to a superclass.

Because Super does not have the ability to represent a reference to a superclass, it simply represents the method that invokes the parent class. Therefore, in the subclass method, it is not possible to use SYSTEM.OUT.PRINTLN (super) or Super.super.mathod ();

In fact, Super.getclass () is the method that represents the invocation of the parent class. The GetClass method comes from the object class, which returns the type of the object at run time. Because the object type at run time is test, This.getclass () and Super.getclass () are returned to test.

In addition, because GetClass () is defined as final in the object class, subclasses cannot override the method, so calling GetClass () in the test method () is in fact invoking the GetClass () method inherited from the parent class. is equivalent to calling the Super.getclass (). GetName () method, so Super.getclass (). The GetName () method should also return test.

If you want the name of the parent class, you should use the following code:

Java 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.