Java 中多态性的一些见解

代码

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());
	}
}

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

图解

猜你喜欢

转载自www.cnblogs.com/zhenqk/p/12771408.html
今日推荐