1 class A{ 2 static int num = 1; 3 public static void Display(){ 4 System.out.println( num ); 5 } 6 } 7 8 class B extends A{ 9 static int num = 2; 10 public static void Display(){ 11 System.out.println( num ); 12 } 13 } 14 15 class C extends A{ 16 static int num = 3; 17 } 18 19 class D extends B{ 20 static int num = 4; 21 } 22 23 public class StaticTest { 24 public static void main(String[] args){ 25 A.Display(); 26 B.Display(); 27 C.Display(); 28 D.Display(); 29 } 30 }
基类中,静态值和静态函数可以被覆盖。但如果要访问继承类中的继承类的值,需要重写方法,不然访问的就是基类的值。
运行结果不是1,2,3,4,而是1,2,1,2。
1 class A{ 2 static int num = 1; 3 int num1 = 2; 4 5 public void Display(){ 6 System.out.println( num + "," + num1 ); 7 } 8 } 9 10 class B extends A{ 11 12 public B(){ 13 num = 3; 14 num1 = 4; 15 } 16 17 @Override 18 public void Display() { 19 // TODO Auto-generated method stub 20 System.out.println( num + "," + num1 ); 21 } 22 } 23 24 class C extends A{ 25 public C(){ 26 num = 5; 27 num1 = 6; 28 } 29 30 } 31 32 public class StaticTest { 33 public static void main(String[] args){ 34 35 A a = new A(); 36 B b = new B(); 37 C c = new C(); 38 39 a.Display(); 40 b.Display(); 41 c.Display(); 42 43 } 44 }
运行结果
5,2
5,4
5,6
多态只是针对非静态成员变量的。静态变量不含this引用,因此不可能实现动态绑定。