java例程练习(多态/动态绑定/迟绑定)

//	实现多态三个条件:
//	1,继承
//	2,父类引用指向子类对象
//	3,重写

public class Test {
	public static void main(String[] args) {
		Cat c = new Cat("KIKI", "Blue");
		Dog d = new Dog("Tom", "Black");
		
		
		Lady l1 = new Lady("Sheery", c);
		Lady l2 = new Lady("Dianl", d);
		
		l1.myPetEnjoy();
		l2.myPetEnjoy();
	}
}

class Animal {
	protected String name;
	Animal(String name) {
		this.name = name;
	}
	
	public void enjoy() {
		System.out.println("Animal cry......");
	}
}

class Cat extends Animal {
	protected String eyeColor;
	Cat(String n, String c) {
		super(n);
		this.eyeColor = c;
	}
	
	public void enjoy() {
		System.out.println("Cat cry......");
	}
}

class Dog extends Animal {
	protected String furColor;
	Dog(String n, String c) {
		super(n);
		this.furColor = c;
	}
	
	public void enjoy() {
		System.out.println("Dog cry......");
	}
}

class Lady {
	protected String name;
	private Animal pet;
	
	Lady(String name, Animal pet) {
		this.name = name;
		this.pet = pet;
	}
	
	public void myPetEnjoy() {
		pet.enjoy();
	}
}












原文地址:https://www.cnblogs.com/wjchang/p/3671713.html