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

时间:2022-05-04
本文章向大家介绍Java继承类中static成员函数的重写,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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