Java 多态

Java 多态性

多态(Polymorphism)的意思是“多种形式”,它发生在我们有许多通过继承相互关联的类时。

就像我们在上一章中指定的那样;继承让我们从另一个类继承属性和方法。多态使用这些方法来执行不同的任务。这允许我们以不同的方式执行单一操作。

例如,请思考名为 Animal 的超类,它有一个名为 animalSound() 的方法。Animals 的子类可以是 Pigs、Cats、Dogs、Birds - 而且它们也有自己的动物声音实现(猪的 oinks 和猫的 meows 等):

实例

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

提示:请回忆在 继承 一章中,我们使用 extends 关键字从类进行继承。

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

实例

class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // 创建 Animal 对象
    Animal myPig = new Pig();  // 创建 Pig 对象
    Animal myDog = new Dog();  // 创建 Dog 对象
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}

亲自试一试

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

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