Polymorphism in Java


Polymorphism allows objects of different classes to be treated as objects of a common super class. It provides flexibility to use a general class reference to refer to a specific subclass object.

Source Code

class Animal {
    void sound() {
        System.out.println("This animal makes a sound.");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("The cat meows.");
    }
}

public class TestPolymorphism {
    public static void main(String[] args) {
        Animal myAnimal = new Cat(); // Cat object is treated as an Animal object
        myAnimal.sound();
    }
}

Polymorphism (many forms) is fundamental in Java, enabling you to write flexible and reusable code with the ability to override or implement methods in subclasses.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments