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 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 } }11 public class Mainclass{12 public static void Main (String ... args) { testClass1 tc1=new testClass2 (); 14 testClass2 tc2 =new testClass2 (), TC1. Smothod (); The output is static in testClass116 TC2. Smothod (); The output is static in testClass217 }18}
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