代码

class animal{
	public void eat() {
		System.out.println("吃饭");
	}
}
class dog extends animal{
	@Override
	//4.吃骨头
	public void eat() {
		System.out.println("吃骨头");
	}
}
class cat extends animal{
	public void eat() {
		System.out.println("吃老鼠");
	}
}
public class duotai {
	//3.调用子类的相应方法 ,如传入new dog()
public void func(animal d) {
	d.eat();
}
	public static void main(String[] args) {
		//1.类的实体化
		duotai dt=new duotai();
		//2.调dt里面的方法,传入子类 new 对象,调谁用谁
		dt.func(new dog());
		dt.func(new cat());
	}
}

可以实现不同子类间的相同方法

图解
Java 中多态性的一些见解

相关文章:

  • 2021-06-04
  • 2022-02-22
  • 2021-04-07
  • 2021-12-16
  • 2021-12-25
  • 2021-04-20
猜你喜欢
  • 2021-10-25
  • 2022-12-23
  • 2021-12-27
  • 2021-09-12
  • 2021-12-05
  • 2021-07-02
相关资源
相似解决方案