Java中static方法是否能被重写
今天再看《Think in Java》中的泛型时,有段关于static相关的的代码搞不清楚。我搞不清出子类继承父类的静态方法和变量之后,在调用静态方法或变量时调用的是谁的。还是用代码来测试一下来说明:
1 package test; 2 3 class Base { 4 5 6 static void staticFunc() { 7 System.out.println("static ---- in base...." ); 8 } 9 10 void func() { 11 System.out.println("in base...." ); 12 } 13 14 } 15 16 class Sub extends Base { 17 18 static void staticFunc() { 19 System.out.println("static ---- in sub..." ); 20 } 21 22 void func() { 23 System.out.println("in sub..." ); 24 } 25 } 26 27 public class test { 28 29 public static void main(String[] args) { 30 Base base = new Sub(); 31 base.staticFunc(); // static ---- in base.... 32 base.func(); // in sub... 33 Base.staticFunc(); 34 35 Sub baseSub = new Sub(); 36 baseSub.staticFunc(); 37 baseSub.func(); 38 Sub.staticFunc(); 39 40 } 41 }
结果:
static ---- in base....
in sub...
static ---- in base....
static ---- in sub...
in sub...
static ---- in sub...
可以看出,影响调用结果的原因是因为在声明时向上转型与否。若是Base则是调用base的static,若是Sub则是sub的static。
Sub是Base的子类,staticFunc应该被重写了才对,但代码显示,父类子类的方法都可以被访问到。也许是static方法并没有被继承,用代码测试一下:
1 package test; 2 3 class Base { 4 5 6 static void staticFunc() { 7 System.out.println("static ---- in base...." ); 8 } 9 10 void func() { 11 System.out.println("in base...." ); 12 } 13 14 } 15 16 class Sub extends Base { 17 18 // static void staticFunc() { 19 // System.out.println("static ---- in sub..." ); 20 // } 21 22 void func() { 23 System.out.println("in sub..." ); 24 } 25 } 26 27 public class test { 28 29 public static void main(String[] args) { 30 Base base = new Sub(); 31 base.staticFunc(); // static ---- in base.... 32 base.func(); // in sub... 33 Base.staticFunc(); 34 35 Sub baseSub = new Sub(); 36 baseSub.staticFunc(); 37 baseSub.func(); 38 Sub.staticFunc(); 39 40 } 41 }
结果:
static ---- in base.... in sub... static ---- in base.... static ---- in base.... in sub... static ---- in base....
可以看到,实际上还是被继承了,那么问题实际上就是,static被继承的子类无法被重写。暂时不太明白,通过查资料得到:对于属性和静态方法来说,调用取决于声明的类型,而对于其他的取决于运行时的类型。

浙公网安备 33010602011771号