Java多型的一個簡單入門的例子

pengfoo發表於2012-05-27
public class Animal {
	public String name;
		
	Animal(String name){
		this.name = name;
	}
	public void enjoy(){
		System.out.println("叫聲");
	}
	
}

/**
 * 
 */

/**
 * @author kuzuozhou
 *
 */
public class Cat extends Animal{
	public String eyesColor;
	Cat(String n, String c){
		super(n);
		eyesColor = c;
	}
	public void enjoy(){
		System.out.println("貓叫聲");
	}

}

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

}

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

}

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Cat c = new Cat("catname","blue");
		Dog d = new Dog("dogname","black");
		
		Lady l1 = new Lady("l1",c);
		Lady l2 = new Lady("l2",d);
		
		l1.myPetEnjoy();
		l2.myPetEnjoy();

	}

}

相關文章