Java继承类中static成员函数的重写

Java继承类中static成员函数的重写
在java中,static成员函数是否可以被重写呢?

结论是,你可以在子类中重写一个static函数,但是这个函数并不能像正常的非static函数那样运行。

也就是说**,虽然你可以定义一个重写函数,但是该函数没有多态特性**。
所以我认为这也是不能用static修饰抽象成员函数的原因,因为静态装载后,再次重写函数,并不能达到重写的效果无多态特性。
让我们测试一下:

 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(); //输出结果为 static in testClass1
16         tc2.SMothod(); //输出结果为 static in testClass2
17     }
18 }

从结果中可以看到,当我们用父类的实例引用(实际上该实例是一个子类)调用static函数时,调用的是父类的static函数。

原因在于方法被加载的顺序

当一个方法被调用时,JVM首先检查其是不是类方法。如果是,则直接从调用该方法引用变量所属类中找到该方法并执行,而不再确定它是否被重写(覆盖)。如果不是,才会去进行其它操作(例如动态方法查询),具体请参考:方法的加载

猜你喜欢

转载自blog.csdn.net/weixin_44627672/article/details/105586137