java 模擬器 多型

nan1010894558發表於2017-10-20

Animal類程式碼:

public abstract class Animal {
	public abstract void cry();
	public abstract String getAnimaName();
}   }

Simulator類程式碼:

public class Simulator {
	public void playSound(Animal animal){
		animal.cry();
		System.out.println(animal.getAnimaName());
	}  }

Dog類程式碼:

public class Dog extends Animal{
	public String name;
	@Override
	public void cry() {
		System.out.println(name+"正在汪汪叫");
	}

	@Override
	public String getAnimaName() {
		return name+"種類為狗";
	}

}



Cat類程式碼:

public class Cat extends Animal{
	public String name;
	
	@Override
	public void cry() {
		System.out.println(name+"正在喵喵叫");
	}

	@Override
	public String getAnimaName() {
		return name+"種類為貓";
	}

}


Test類程式碼:

public class Test {

	public static void main(String[] args) {
		Simulator simulator=new Simulator();
		Animal p1=new Dog();
		Animal p2=new Cat();
		Dog dog=(Dog)p1;
		dog.name="西西";
		Cat cat=(Cat)p2;
		cat.name="花花";
		simulator.playSound(p1);
		simulator.playSound(p2);
	}

}




執行結果圖:

相關文章