Java 多态性

Java 多态

多态性意味着 "多种形式",当我们有许多通过继承相互关联的类时,就会发生多态。

如前一章所述;继承 允许我们从另一个类继承属性和方法。多态性 使用这些方法来执行不同的任务。这允许我们以不同的方式执行单个操作。

例如,考虑一个名为 Animal 的超类,它有一个名为 animalSound() 的方法。动物的亚类可以是猪、猫、狗、鸟,它们也有自己的动物声音(猪叫、猫叫等):

实例
  1. class Animal {
  2. public void animalSound() {
  3. System.out.println("The animal makes a sound");
  4. }
  5. }
  6. class Pig extends Animal {
  7. public void animalSound() {
  8. System.out.println("The pig says: wee wee");
  9. }
  10. }
  11. class Dog extends Animal {
  12. public void animalSound() {
  13. System.out.println("The dog says: bow wow");
  14. }
  15. }
请记住,在继承一章中,我们使用 extends 关键字从类继承。

现在我们可以创建 PigDog 对象,并对它们调用 animalSound() 方法:

实例
  1. class Animal {
  2. public void animalSound() {
  3. System.out.println("The animal makes a sound");
  4. }
  5. }
  6. class Pig extends Animal {
  7. public void animalSound() {
  8. System.out.println("The pig says: wee wee");
  9. }
  10. }
  11. class Dog extends Animal {
  12. public void animalSound() {
  13. System.out.println("The dog says: bow wow");
  14. }
  15. }
  16. public class Main {
  17. public static void main(String[] args) {
  18. Animal myAnimal = new Animal();
  19. Animal myPig = new Pig();
  20. Animal myDog = new Dog();
  21. myAnimal.animalSound();
  22. myPig.animalSound();
  23. myDog.animalSound();
  24. }
  25. }

为什么以及何时使用 “继承” 和 “多态”?

  • 它对代码的可重用性很有用:在创建新类时重用现有类的属性和方法。