Java Polymorphism
Polymorphism is the ability of a parent type to hold objects of different child classes. A single method call then runs the version that belongs to the actual object.
The same call, two different sounds
Both variables have the type Animal. One holds a Dog and the other holds a Cat.
public class Main {
public static void main(String[] args) {
Animal first = new Dog();
Animal second = new Cat();
first.sound();
second.sound();
}
}
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}A parent object uses the parent version
The first variable holds a plain Animal object. The second variable holds a Dog object.
public class Main {
public static void main(String[] args) {
Animal first = new Animal();
Animal second = new Dog();
first.sound();
second.sound();
}
}
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}A method accepts the parent type
The makeSound method takes an Animal value. A Dog and a Cat can both be passed to it.
public class Main {
static void makeSound(Animal animal) {
animal.sound();
}
public static void main(String[] args) {
makeSound(new Dog());
makeSound(new Cat());
}
}
class Animal {
void sound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}Example
public class Main {
public static void main(String[] args) {
Shape first = new Circle();
Shape second = new Square();
first.draw();
second.draw();
}
}
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
void draw() {
System.out.println("Drawing a square");
}
}Key points
- A variable of a parent type can hold an object of a child type.
- A child class overrides a parent method by writing a method with the same name.
- Java chooses the method version from the actual object when the program runs.
- The same call on two child objects can print two different lines.
- A parent method that no child overrides runs as written in the parent.
In this example, both variables have the type Shape. The first holds a Circle and the second holds a Square. Both calls use the name draw. Each call runs the version from the object it is called on.
Note
Polymorphism works through inheritance, so each child must extend the parent.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
An Animal variable holds a Dog object, and sound is called on it. Which version runs?