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