重写方法的目的是为了多态,或者说:重写是实现多态的前提,即重写是发生在继承中且是针对非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();
	}
}

  

相关文章:

  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2021-07-07
  • 2022-12-23
  • 2021-11-02
相关资源
相似解决方案