静态方法能不能被覆盖呢?先看一个例子:
public class Base{ //父类
public static int a=10;
public static void staticMethod(){
System.out.println("StaticMethod of Base");
}
public void method(){
System.out.println("Method of Base");
}
}
//Sub是继承Base的子类
public class Sub extends Base{
public static int a=30;
public static void staticMethod(){//与Base类的静态方法相同
System.out.println("StaticMethod of Sub");
}
public void method(){//覆盖父类实例方法method()
System.out.println("Method of Sub");
}
}
//Test对上述两个类进行测试
public class Test{
public static void main(String[] args){
Base sub1=new Sub(); //创建Sub类实例并赋给Base类的引用变量
Sub sub2=new Sub();
sub1.staticMethod();
sub1.method();
System.out.println(sub1.a);
sub2.staticMethod();
sub2.method();
System.out.println(sub2.a);
}
}
//执行结果如下:
StaticMethod of Base
Method of Sub
10
StaticMethod of Sub
Method of Sub
30
从上面的执行结果可以看出Base类的静态方法并没有被子类Sub的静态方法覆盖,只是对其进行了隐藏。另外也可以看出静态成员只与类有关!