📜  Java 多态 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:45.709000             🧑  作者: Mango

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

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

class Dog extends Animal {                    //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();  // Create a Animal object
    Animal myPig = new Pig();  // Create a Pig object
    Animal myDog = new Dog();  // Create a Dog object
    myAnimal.animalSound();
    myPig.animalSound();
    myDog.animalSound();
  }
}