Introduction
Polymorphism helps us use one interface to work with different types of objects. It makes code easier to write and change.
Jump into concepts and practice - no test required
Polymorphism helps us use one interface to work with different types of objects. It makes code easier to write and change.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal a; a = new Dog(); a.sound(); a = new Cat(); a.sound(); } }
Polymorphism is often done using method overriding in Java.
It allows one variable to refer to objects of different classes.
a is of type Animal but holds a Dog object. The sound() method of Dog runs.Animal a = new Dog(); a.sound(); // Prints: Dog barks
a holds a Cat object, so Cat's sound() runs.Animal a = new Cat(); a.sound(); // Prints: Cat meows
a holds an Animal object, the base method runs.Animal a = new Animal(); a.sound(); // Prints: Animal makes a sound
This program shows how one variable a can hold different objects and call their own sound() methods. This is polymorphism in action.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal a; a = new Dog(); a.sound(); a = new Cat(); a.sound(); a = new Animal(); a.sound(); } }
Polymorphism helps keep code flexible and easy to extend.
It reduces the need for many if or switch statements.
Polymorphism lets one name work for many forms.
It allows writing general code that works with many object types.
This makes programs easier to maintain and grow.
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void sound() { System.out.println("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
void bark() { System.out.println("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
a.bark();
}
}