Java Polymorphism
Language: Java
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound(); // prints Woof
a = new Cat();
a.makeSound(); // prints Meow
}
}Output
Click Run to execute this code.