Override of static member functions in the Java inheritance class, javastatic

Source: Internet
Author: User

Override of static member functions in the Java inheritance class, javastatic

In java, can static member functions be overwritten?

The conclusion is that you can override a static function in the subclass, but this function does not run as normal non-static functions.

That is to say, although you can define an rewrite function, this function has no polymorphism. Let's test:

1 class testClass1 {2 static void SMothod () {3 System. out. println ("static in testClass1"); 4} 5} 6 class testClass2 extends testClass1 {7 static void SMothod () {8 System. out. println ("static in testClass2"); 9} 10} 11 public class MainClass {12 public static void main (String... args) {13 testClass1 tc1 = new testClass2 (); 14 testClass2 tc2 = new testClass2 (); 15 tc1.SMothod (); // The output result is static in testClass116 tc2.SMothod (); // The output result is static in testClass217} 18}

From the results, we can see that when we call the static function using the instance reference of the parent class (in fact, this instance is a subclass), it calls the static function of the parent class.

The reason is the order in which methods are loaded.

When a method is called, JVM first checks whether it is a class method. If yes, the method is directly found and executed from the class that calls this method to reference the variable, instead of determining whether it is overwritten ). If not, other operations (such as dynamic method query) will be performed. For details, see loading methods.

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.