overriding of static member functions in Java inheriting classes

Source: Internet
Author: User

In Java, can static member functions be overridden?

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

In other words, although you can define an overriding function, the function has no polymorphic properties. Let's Test it:

1 classtestclass1{2     Static voidSmothod () {3System.out.println ("Static in TestClass1");4     }5 }6 classTestClass2extendstestclass1{7     Static voidSmothod () {8System.out.println ("Static in TestClass2");9     }Ten } One  Public classmainclass{ A      Public Static voidMain (String ... args) { -TestClass1 tc1=NewTestClass2 (); -TestClass2 TC2 =NewTestClass2 (); theTC1. Smothod ();//the output is static in TestClass1 -Tc2. Smothod ();//the output is static in TestClass2 -     } -}

As you can see from the results, the static function of the parent class is called when we call the static function with the instance reference of the parent class, which is actually a subclass of the instance.

The reason is the order in which the methods are loaded.

When a method is called, the JVM first checks that it is not a class method. If so, the method is found and executed directly from the class that called the method reference variable, and is no longer determined whether it is overridden (overwritten). If not, do other things (such as dynamic method queries), see: Loading of methods

overriding of static member functions in Java inheriting classes

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.