2013-12-06

[Java]多載(Overload)與覆寫(Override)

每星期五之John大師開釋

public class Animal {
	public int leg;
	public String name;

	public Animal() {
		this(2, "no-name");
	}

	public Animal(int leg, String name) {
		this.leg = leg;
		this.name = name;
	}
	//當呼叫Animal呼叫時會依照傳入參數,自動決定呼叫哪一個Method,稱之為多載(Overload)
	public void eat() {
		System.out.println("「動物」吃東西");
	}

	public static void main(String[] args) {
		Animal animal = new Dog();
		animal.eat();
		//Class Dog 繼承(extends) Class Animal,當呼叫時覆寫(Override)子類別覆寫母類別,所以會印出"「狗」吃東西",而非"「動物」吃東西"
		Dog dog = new Dog();
		dog.eat();

		Cat cat = new Cat();
		cat.eat();

	}
}

class Dog extends Animal {
	public void eat() {
		System.out.println("「狗」吃東西");
	}
}

class Cat extends Animal {
	public void eat() {
		System.out.println("「貓」吃東西");
	}
}

沒有留言:

張貼留言