首页 > 学院 > 开发设计 > 正文

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

2019-11-15 00:57:54
字体:
来源:转载
供稿:网友
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 testClass116         tc2.SMothod(); //输出结果为 static in testClass217     }18 }

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

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

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表