java static方法不能被重写原因

重写方法的目的是为了多态,或者说:重写是实现多态的前提,即重写是发生在继承中且是针对非static方法的。

语法上子类允许出现和父类只有方法体不一样其他都一模一样的static方法,但是在父类引用指向子类对象时,通过父类引用调用的依然是父类的static方法,而不是子类的static方法。

即:语法上static支持重写,但是运行效果上达不到多态目的
class Father {
public static void staticMethod() {
System.out.println(“Father”);
}
}

class Son extends Father {
// @Override 因为从逻辑上达不到重写的目的,所以这里添加 @Override 会编译报错
public static void staticMethod() {
System.out.println(“Son”);
}
}

public class M {
public static void main(String[] args) {
Father mByFather = new Father();
Father mBySon = new Son();
Son son = new Son();

	mByFather.staticMethod();
	mBySon.staticMethod();  // 这里返回的是Father而不是Son, static方法上重写不会报错,但是从逻辑运行效果上来看达不到多态的目的
	son.staticMethod();
}

}

猜你喜欢

转载自blog.csdn.net/weixin_41050155/article/details/82747130
今日推荐