静态方法为什么不能被重写

首先我们来测试,猜下下面程序的运行结果...

 1 // 该类测试静态方法为什么不能被重写
 2 public class Test1_Static {
 3     
 4     public static void main(String[] args) {
 5         Father f = new Father(); 
 6         f.staticMethod();  
 7         Child c = new Child();
 8         c.staticMethod(); 
 9         Father person = new Child();
10         person.staticMethod();  
11         
12     }
13 }
14 
15 
16 class Father {
17     public static void staticMethod() {
18         System.out.println("fatherMethod");
19     }
20 }
21 
22 class Child extends Father{
23     public static void staticMethod() {
24         System.out.println("childMethod");
25     }
26 }

打印结果:

fatherMethod
childMethod
fatherMethod

相信前两个打印结果大家都已经猜到了,但是最后一个结果相信有不少小伙伴会产生疑惑,甚至做出错误的判断,其实一个指向子类对象的父类引用变量来调用父子同名的静态方法时,只会调用父类的静态方法。这是因为静态方法只能被继承,不能被重写,如果子类有和父类相同的静态方法,那么父类的静态方法将会被隐藏,对于子类不可见,也就是说,子类和父类中相同的静态方法是没有关系的方法,他们的行为不具有多态性。但是父类的静态方法可以通过父类.方法名调用。

这个文档也不错,可参考下:关于静态方法为什么不能被重写的一点思考以及overload的一些坑。

猜你喜欢

转载自www.cnblogs.com/love-programming/p/12458693.html
今日推荐