Đa hình (Polymorphism)

Ví dụ

class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Cat extends Animal {
public void animalSound() {
System.out.println("The cat says: meow!");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: woof!");
}
}
class Cow extends Animal {
public void animalSound() {
System.out.println("The cow says: moo!");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
Animal myCow = new Cow(); // Create a Cow object
myAnimal.animalSound();
myCat.animalSound();
myDog.animalSound();
myCow.animalSound();
}
}
class Animal { public void animalSound() { System.out.println("The animal makes a sound"); } } class Cat extends Animal { public void animalSound() { System.out.println("The cat says: meow!"); } } class Dog extends Animal { public void animalSound() { System.out.println("The dog says: woof!"); } } class Cow extends Animal { public void animalSound() { System.out.println("The cow says: moo!"); } } class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); // Create a Animal object Animal myCat = new Cat(); // Create a Cat object Animal myDog = new Dog(); // Create a Dog object Animal myCow = new Cow(); // Create a Cow object myAnimal.animalSound(); myCat.animalSound(); myDog.animalSound(); myCow.animalSound(); } }
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Cat extends Animal {
  public void animalSound() {
    System.out.println("The cat says: meow!");
  }
}

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

class Cow extends Animal {
  public void animalSound() {
    System.out.println("The cow says: moo!");
  }
}

class Main {
  public static void main(String[] args) {
    Animal myAnimal = new Animal();  // Create a Animal object
    Animal myCat = new Cat();  // Create a Cat object
    Animal myDog = new Dog();  // Create a Dog object
    Animal myCow = new Cow();  // Create a Cow object
    myAnimal.animalSound();
    myCat.animalSound();
    myDog.animalSound();
    myCow.animalSound();
  }
}