OBJECT-ORIENTED PROGRAMMING

Java polymorphism

Polymorphism means “many forms”. It lets you use objects of different subclasses through a common base type, with each object handling the same method call differently.

Inheritance and polymorphism

Inheritance connects a base class to its subclasses. Polymorphism uses that connection: a base-class reference can point to different subclass objects, and an overridden method is chosen based on the actual object.

Different behavior for the same method

Books, magazines and newspapers are publications, but each introduces itself differently:

class Leidinys {
    public void rodytiTipa() {
        System.out.println("Tai yra leidinys");
    }
}

class Knyga extends Leidinys {
    @Override
    public void rodytiTipa() {
        System.out.println("Tai yra knyga");
    }
}

class Zurnalas extends Leidinys {
    @Override
    public void rodytiTipa() {
        System.out.println("Tai yra žurnalas");
    }
}

class Laikrastis extends Leidinys {
    @Override
    public void rodytiTipa() {
        System.out.println("Tai yra laikraštis");
    }
}
  1. Leidinys is a shared base class with the method rodytiTipa().
  2. Knyga, Zurnalas and Laikrastis extend this class.
  3. Each subclass overrides the same method and produces its own result.
  4. This block creates no objects and calls no methods yet, so nothing appears in the console.

A base-class reference

public class Main {
    public static void main(String[] args) {
        Leidinys pirmas = new Leidinys();
        Leidinys antras = new Knyga();
        Leidinys trecias = new Zurnalas();

        pirmas.rodytiTipa();
        antras.rodytiTipa();
        trecias.rodytiTipa();
    }
}
Console output

Tai yra leidinys
Tai yra knyga
Tai yra žurnalas

  1. All three variables are declared with the common type Leidinys.
  2. However, antras stores an actual Knyga, while trecias – Zurnalas object.
  3. At runtime, Java looks at the actual object and selects its rodytiTipa() version.
  4. Identically written method calls therefore produce different results.

Different objects in one array

A common type lets one collection hold objects of different subclasses:

public class Main {
    public static void main(String[] args) {
        Leidinys[] leidiniai = {
            new Knyga(),
            new Zurnalas(),
            new Laikrastis()
        };

        for (Leidinys leidinys : leidiniai) {
            leidinys.rodytiTipa();
        }
    }
}
Console output

Tai yra knyga
Tai yra žurnalas
Tai yra laikraštis

  1. Leidinys[] array can hold all objects that are instances of Leidinys or its subclasses.
  2. for-each loop takes one publication at a time.
  3. The loop does not need to check whether an element is a book, magazine or newspaper.
  4. Each object runs its own overridden method.

A common method parameter

A method accepting a base type can work with any of its subclasses:

public class Main {
    static void pristatyti(Leidinys leidinys) {
        leidinys.rodytiTipa();
    }

    public static void main(String[] args) {
        pristatyti(new Knyga());
        pristatyti(new Laikrastis());
    }
}
Console output

Tai yra knyga
Tai yra laikraštis

  1. The method pristatyti() accepts a parameter of the common Leidinys type.
  2. It can receive either Knygaand Laikrastis object.
  3. Adding a new publication subclass usually requires no changes to the method pristatyti() itself.

Reference type and object type

class Knyga extends Leidinys {
    public void atverstiPuslapi() {
        System.out.println("Puslapis atverstas");
    }
}

public class Main {
    public static void main(String[] args) {
        Leidinys leidinys = new Knyga();

        leidinys.rodytiTipa();
        // leidinys.atverstiPuslapi(); // Compilation error
    }
}
Console output

Tai yra knyga

The object is actually a Knyga, so the book's overridden method runs. However, the reference is declared as Leidinys, so it cannot directly call the book-only method atverstiPuslapi().

Roles of polymorphic reference and object types
TypeWhat does it determine?
Declared reference typeWhich members the compiler allows access to
Actual object typeWhich overridden method implementation runs

Be careful with casting

You can try casting a base-class reference to a subclass, but the object must actually have that type:

Leidinys leidinys = new Zurnalas();

// Runtime error: the object is not a Knyga
Knyga knyga = (Knyga) leidinys;
Runtime error

java.lang.ClassCastException: Zurnalas cannot be cast to Knyga

  1. The variable leidinys actually stores a Zurnalas object.
  2. Writing a type in parentheses does not turn a magazine into a book.
  3. The program compiles, but the invalid assumption is detected at runtime.
  4. Well-designed polymorphic code often needs no such cast.

Why use polymorphism?

  • One piece of code can process many related object types.
  • New subclasses can be added with fewer changes to existing code.
  • Type checks and long if...else chains often become unnecessary.
  • Each class is responsible for its own method implementation.
  • The inherited common interface and specialized behavior remain clearly separated.