子类已经覆盖了父类的静态方法,应该运行子类的静态方法才对呀? package hidestatic; class Base{ void method(){ system.out.println("method of Base"); } static void staticMethod(){ System.out.println("static method of Base"); } } public class Sub extends Base{ void method(){ System.out.println("method of Sub"); } static void staticMethod(){ System.out.println("static method of Sub"); }
public static void main(String args[]){ Base sub1=new Sub(); sub1.method(); sub1.staticMethod();
Sub sub2=new Sub(); sub2.method(); sub.staticMethod(); } }
运行结果:method of Sub static method of Base method of Sub static method of Sub
为什么:sub1.staticMethod()的运行结果是:static method of Base ? 按理说,子类已经覆盖父类的静态方法了,应该运行子类的静态方法才对呀,为什么还是调用父类的静态方法?
class Person{
public static void fun(){
System.out.println("父类");
}
}
class Child extends Person{
public static void fun(){
System.out.println("子类");
}
}
public class Test{
public static void main(String args[]){
Person p = new Child();//因为左边的是Person类型,所以调用Person静态方法。
p.fun();//静态方法的调用对象是在编译时就决定的。
}
}
------解决方案--------------------