← Chapter 6 — Object-Oriented Programming

26. Polymorphism, Abstract Classes & Interfaces

mixed

Description

Polymorphism lets code work through a shared type while objects provide their own implementation. It reduces duplicate code when several classes can perform the same action.

Abstract classes can share partial implementation. Interfaces define a contract that unrelated classes can implement.

Subtopics

Overriding

Description

A child can replace inherited behavior.

Explanation

@Override asks the compiler to verify the method signature.

Example

@Override
void study() { System.out.println("Research"); }

Interfaces

Description

An interface defines behavior a class promises to provide.

Explanation

A class can implement more than one interface.

Example

interface Printable { void print(); }

Explanation

Declare variables with the most useful shared type, such as Printable item. This allows different implementations to be substituted without changing the calling code.

Example

public class PolymorphismDemo {
    interface Greeter { void greet(); }
    static class Student implements Greeter {
        public void greet() { System.out.println("Hello from Aditi"); }
    }
    public static void main(String[] args) {
        Greeter learner = new Student();
        learner.greet();
    }
}

Key points

  • Polymorphism uses a shared type.
  • @Override verifies overridden methods.
  • Interfaces define contracts.

Open reference