今天在Github上看到这样一句话让我一下没反应过来:如果父类方法访问修饰符为 private/final/static 则子类就不能重写该方法,但是被 static 修饰的方法能够被再次声明。
我寻思着static方法不是不能重写吗?于是做了如下实验:
1 class Base { 2 public static String staticBase() { 3 return "Base-staticBase()"; 4 } 5 6 public String normal() { 7 return "Base-normal()"; 8 } 9 } 10 11 class Son extends Base{ 12 public static String staticBase() { 13 return "Son-staticBase()"; 14 } 15 16 public String normal() { 17 return "son-normal()"; 18 } 19 } 20 21 public class StaticTest { 22 public static void main(String[] args) { 23 Base son = new Son(); 24 System.out.println(son.staticBase()); 25 System.out.println(son.normal()); 26 } 27 }
结果如下:
可以看见静态方法依旧没有被重写,他只是被重复声明,相当于另一个方法,与原来不相干,写着写着突然明白了...