Java作為一種面向對象的編程語言,繼承和多態是其非常重要的特性之一。在設計動物類時,利用繼承和多態的特性可以讓代碼更加簡潔、易讀,同時也提高了代碼的可擴展性和重用性。
我們可以首先定義一個Animal類,然后創建幾個子類比如Cat,Dog和Bird。其中Animal類定義了一系列的共同特征和操作,如呼吸、進食等,而各個子類又擁有自身獨特的特征和操作。
public class Animal { private String name; private int age; // Constructor public Animal(String name, int age) { this.name = name; this.age = age; } // Getter and Setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } // Common behaviors of animals public void breathe() { System.out.println(this.name + " is breathing."); } public void eat() { System.out.println(this.name + " is eating."); } } public class Cat extends Animal{ private String coatColor; // Constructor public Cat(String name, int age, String coatColor) { super(name, age); this.coatColor = coatColor; } // Getter and Setter method public String getCoatColor() { return coatColor; } public void setCoatColor(String coatColor) { this.coatColor = coatColor; } // Unique behavior of cat public void meow() { System.out.println(this.getName() + " is meowing."); } } public class Dog extends Animal{ private String breed; // Constructor public Dog(String name, int age, String breed) { super(name, age); this.breed = breed; } // Getter and Setter method public String getBreed() { return breed; } public void setBreed(String breed) { this.breed = breed; } // Unique behavior of dog public void bark() { System.out.println(this.getName() + " is barking."); } } public class Bird extends Animal{ private String featherColor; // Constructor public Bird(String name, int age, String featherColor) { super(name, age); this.featherColor = featherColor; } // Getter and Setter method public String getFeatherColor() { return featherColor; } public void setFeatherColor(String featherColor) { this.featherColor = featherColor; } // Unique behavior of bird public void fly() { System.out.println(this.getName() + " is flying."); } }
在使用繼承和多態的時候,我們可以聲明一個Animal類型的引用變量,并將其指向Cat,Dog或者Bird的對象,從而使得這個引用變量可以執行相應的方法。這樣做有很多好處,比如可以降低代碼的復雜度,提高代碼的可讀性。
public static void main(String[] args) { Animal cat = new Cat("Tom", 3, "gray"); Animal dog = new Dog("Spike", 2, "Bulldog"); Animal bird = new Bird("Tweety", 1, "yellow"); // Calling common behaviors of animals cat.breathe(); dog.eat(); bird.eat(); // Calling unique behaviors if(cat instanceof Cat) { ((Cat) cat).meow(); } if(dog instanceof Dog) { ((Dog) dog).bark(); } if(bird instanceof Bird) { ((Bird) bird).fly(); } }
通過運行上面的程序,我們可以看到貓、狗和鳥分別執行了它們自己的獨特方法,同時也能夠呼吸和進食。這就是繼承和多態的好處所在。