DEV Community

Bharath kumar
Bharath kumar

Posted on

Polymorphism in Java

What is polymorphism?
The word polymorphism means having many forms.

The same method can behave differently depending on the object that calls this method.

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(); // 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();
}
}

Output:
The animal makes a sound
The pig says: wee wee
The dog says: bow wow

Reference :https://www.w3schools.com/java/java_polymorphism.asp

Top comments (0)