Polymorphism: Many Forms

One variable, many kinds of object

A variable of the parent type can hold any child object. When you call a method, Java runs the version of the real object. This is polymorphism (Greek for “many forms”):

class Shape {
    double area() {
        return 0;
    }
}

class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }

    @Override
    double area() {
        return Math.PI * r * r;
    }
}

class Square extends Shape {
    double side;
    Square(double side) { this.side = side; }

    @Override
    double area() {
        return side * side;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape[] shapes = {new Circle(1), new Square(3), new Circle(2)};
        double total = 0;
        for (Shape s : shapes) {
            System.out.printf("%.2f%n", s.area());
            total += s.area();
        }
        System.out.printf("Total: %.2f%n", total);
    }
}

Output

3.14
9.00
12.57
Total: 24.71

Think of it like this: A TV remote has one “power” button. Press it on a Samsung TV or a Sony TV – each TV turns on in its own way, but you only need to know about the one button.

The loop doesn't care what kind of shape it has. If you add a Triangle class later, the loop works without any change.

Checking the real type: instanceof

class Animal { }
class Dog extends Animal {
    void fetch() { System.out.println("Fetching the ball!"); }
}
class Cat extends Animal { }

public class Main {
    public static void main(String[] args) {
        Animal[] pets = {new Dog(), new Cat()};
        for (Animal a : pets) {
            if (a instanceof Dog) {
                Dog d = (Dog) a;
                d.fetch();
            } else {
                System.out.println("This pet doesn't fetch.");
            }
        }
    }
}

Output

Fetching the ball!
This pet doesn't fetch.

Through an Animal variable you can only call Animal methods. To use fetch() you first check with instanceof, then cast to Dog.

HOME LABS COMMUNITY DASHBOARD