FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Object-Oriented Programming

CSE

Progress0 / 6 lessons
  1. 1. What a class models, and why OOP was invented
  2. 2. Encapsulation, and why getters exist
  3. 3. Inheritance, and when NOT to use it
  4. 4. Polymorphism, with a runnable example
  5. 5. Abstraction: interfaces versus abstract classes
  6. 6. The SOLID principles in plain English

Courses › Object-Oriented Programming

Polymorphism, with a runnable example

One loop that handles types it has never heard of, and the difference between overloading and overriding.

12 min read · Lesson 4 of 6 · Pro

The problem, in code you have probably written

Java
for (Object o : things) {
    if (o instanceof Circle) {
        total += ((Circle) o).circleArea();
    } else if (o instanceof Rect) {
        total += ((Rect) o).rectArea();
    } else if (o instanceof Triangle) {
        total += ((Triangle) o).triangleArea();
    }
}

Every new shape means editing this loop. If the same chain appears in five files, that is five edits, and you will forget one. This is the shape of code that polymorphism deletes.

The polymorphic version

Java
abstract class Shape {
    abstract double area();
The rest of this lesson is Pro

The free lessons of Object-Oriented Programming finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.