Đa hình (Polymorphism)
OOP_Polymorphism Ví dụ
java
1class Animal {2 public void animalSound() {3 System.out.println("The animal makes a sound");4 }5}6 7class Cat extends Animal {8 public void animalSound() {9 System.out.println("The cat says: meow!");10 }11}12 13class Dog extends Animal {14 public void animalSound() {15 System.out.println("The dog says: woof!");16 }17}18 19class Cow extends Animal {20 public void animalSound() {21 System.out.println("The cow says: moo!");22 }23}24 25class Main {26 public static void main(String[] args) {27 Animal myAnimal = new Animal(); // Create a Animal object28 Animal myCat = new Cat(); // Create a Cat object29 Animal myDog = new Dog(); // Create a Dog object30 Animal myCow = new Cow(); // Create a Cow object31 myAnimal.animalSound();32 myCat.animalSound();33 myDog.animalSound();34 myCow.animalSound();35 }36}
