R
Rishtaara
Java Fundamentals
Lesson 20 of 36Article16 min

Polymorphism

Same reference type can point to different object types: Animal a = new Dog();

Polymorphism — many forms

Same reference type can point to different object types: Animal a = new Dog();

Method overriding — child replaces parent method with same signature.

Real-life example: Remote control button "Play" — same button, different device (TV plays video, speaker plays music).

Method overriding
class Shape {
    void draw() {
        System.out.println("Drawing shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing circle");
    }
}

Shape s = new Circle();
s.draw(); // Drawing circle

Runtime polymorphism

Java picks the actual object type at runtime for overridden methods.

Useful for arrays or lists of mixed subclasses: Shape[] shapes = { new Circle(), new Square() };

Real-life example: A school announcement says "all students line up" — each student walks differently, but one command fits all.

Polymorphic array
class Square extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing square");
    }
}

Shape[] shapes = { new Circle(), new Square() };
for (Shape sh : shapes) {
    sh.draw();
}