IAE Academy

FOR CORE AND IT JOBS · CHAPTER 4 OF 7

Polymorphism, abstract classes and interfaces

This chapter explains how one call can run different code depending on the object behind it, and how abstract classes and interfaces set the contract that makes this safe. An engineer needs it to write code that accepts new kinds of objects without being edited.

Updated 30 Oct 2026

What you will be able to do

You will trace a call through a superclass reference and say which method runs, and when that was decided. You will tell overloading from overriding. You will write abstract classes and interfaces, use casts and instanceof safely, and choose between an abstract class and an interface.

Before you start

  1. Chapter 3, Inheritance

  2. Java 17 basics: classes, constructors, fields, methods, the keywords static and final, arrays, if, for, null references and exceptions

  3. Access modifiers public and private, and the default (package) access when none is written

  4. java.util's List, ArrayList and LinkedList by name, import lines, and the diamond in new ArrayList<>()

One call, many behaviours

A variable has a declared type, written before its name. The object it holds has an actual type, the class named after new. A superclass variable may hold a subclass object. The compiler picks a method's signature (its name and parameter types) from the declared type; when that method is overridden, the body that runs comes from the actual type. In describe below, area() means this.area(). The Circle takes so the numbers stay round.

class Shape {
    double area() { return 0; }
    String describe() { return "area " + area(); }
}
class Square extends Shape {
    double side;
    Square(double side) { this.side = side; }
    @Override double area() { return side * side; }
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    @Override double area() { return 3 * r * r; }
}
public class Demo {
    public static void main(String[] args) {
        Shape s = new Square(2);
        System.out.println(s.describe()); // area 4.0
        s = new Circle(1);
        System.out.println(s.describe()); // area 3.0
    }
}

DYNAMIC DISPATCH

For an instance method that is not private and not called through super. The search is for the signature the compiler chose; if no class has a body, an interface's default method runs. Static methods and fields use the declared type.

Overloading

Overriding

Signature

Parameter list differs

Parameter list identical

Decided

At compile time

At run time

Decided by

Declared types of the arguments

Actual class of the object

Applies to

Any method or constructor

Instance methods, not private or final

OVERLOAD RESOLUTION

Among the overloads that accept the arguments; if none is most specific, the call does not compile.

WORKED EXAMPLE

Given

class Animal {
    String sound() { return "..."; }
    String speak() { return "I say " + sound(); }
}
class Dog extends Animal {
    @Override String sound() { return "Woof"; }
}
class Puppy extends Dog {
    @Override String sound() { return super.sound() + "!"; }
}

what does Animal a = new Puppy(); System.out.println(a.speak()); print?

Solution
  1. The declared type is Animal and the actual type is Puppy, so dispatch starts at Puppy.

  2. Neither Puppy nor Dog defines speak, so Animal's speak runs.

  3. Inside speak, sound() means this.sound(). The object is a Puppy, so Puppy's sound runs.

  4. super.sound() is not dispatched: it runs Dog's version, "Woof", and Puppy adds "!".

  5. speak joins "I say " and "Woof!".

Answer: I say Woof!

WORKED EXAMPLE

Given

class Printer {
    static String show(Shape s)  { return "shape"; }
    static String show(Square q) { return "square"; }
}

and Shape s = new Square(2); Square q = new Square(2); what do Printer.show(s), Printer.show(q) and Printer.show((Square) s) return?

Solution
  1. This is overloading, so the compiler chooses from the declared types of the arguments.

  2. s is declared Shape, so only show(Shape) accepts it: "shape", although the object is a Square.

  3. q is declared Square. Both versions accept it, and the more specific show(Square) wins: "square".

  4. The cast (Square) s gives the expression the type Square (casts are covered in the last section), so show(Square) is chosen. The cast succeeds at run time because the object is a Square: "square".

Answer: shape, square, square

Abstract classes and interfaces

Sometimes a superclass has no sensible body for a method: a generic Shape cannot know its area. Declare the method abstract and give it no body. The class must then be declared abstract too, and new cannot create an object of it. Here is Shape rewritten that way.

abstract class Shape {
    abstract double area();
    String describe() { return "area " + area(); }
}
// new Shape() does not compile; new Square(2) still does

ABSTRACT CLASS RULE

A concrete class is one not declared abstract; the body may be its own or inherited. An abstract class may still hold fields, constructors and ordinary methods.

An interface lists methods a class promises to provide, and holds no instance fields. A class extends one parent class but can implement any number of interfaces. A default method gives implementers a ready-made body, which they may override.

interface Drawable { void draw(); }
interface Resizable {
    void resize(int percent);
    default String hint() { return "resizable"; }
}
class Icon implements Drawable, Resizable {
    public void draw() { System.out.println("icon"); }
    public void resize(int percent) {
        System.out.println("icon at " + percent + "%");
    }
}
// new Icon().hint() returns "resizable"

INTERFACE RULE

C is a class and I an interface. C, or a superclass of C, must give a public body for every abstract method of I; otherwise C must be declared abstract.

Two interfaces that do not extend each other may give default methods with the same signature, say hello() in Greeter and Welcomer. A class implementing both must override hello or it does not compile. In that override, return Greeter.super.hello(); runs Greeter's version. Exception: a public method body inherited from a superclass takes priority over the defaults, so no override is needed.

WATCH OUT FOR

Leaving out public when implementing an interface method. Interface methods written without an access modifier are public, and an override may not reduce access. Test: compile it; the error reads "attempting to assign weaker access privileges".

To choose between the two, ask what is shared. Code and fields shared by closely related classes point to an abstract class. A capability that unrelated classes can have, such as being drawable, points to an interface.

Programming to an interface, and casts

List is an interface; ArrayList and LinkedList are classes that implement it. Use the general type for variables, parameters and return types, and name the class only after new: List<String> names = new ArrayList<>();. Later lines can use only what List promises, so switching to LinkedList changes only that line and its import.

Moving up to a general type is an upcast. It is automatic and always safe, because a Square is a Shape. Moving down is a downcast. It needs a written cast and is checked at run time: if the object is not of the cast type, Java throws a ClassCastException. In Java 17, s instanceof Square q tests the actual class and, when true, gives you q: the same object, typed as Square.

public class Casts {
    public static void main(String[] args) {
        Shape s = new Square(2);      // upcast: automatic
        // double x = s.side;         // does not compile: Shape has no side
        if (s instanceof Square q) {  // true: actual class is Square
            System.out.println(q.side); // 2.0
        }
        // Circle c = (Circle) s;     // compiles, then ClassCastException
    }
}

CAST RULE

For a non-null reference and a cast the compiler accepts (it refuses one between two classes when neither extends the other). T is the target class or interface. A subtype: the class extends T or, for an interface T, it or a superclass implements T or an interface extending T.

MEMBER ACCESS RULE

For a field or method used through a variable or expression, where its access modifier allows the use; the actual class plays no part.

Check yourself

CHECK YOURSELF 1

Which statement about Java is true?

  1. (A)

    A class can extend two abstract classes

  2. (B)

    A class can implement two interfaces

  3. (C)

    An interface can have instance fields that hold state

  4. (D)

    An abstract class can be created with new

Answer and solution

Answer: (B)

  1. A class has one parent class, so A is false.

  2. Implementing several interfaces is allowed, so B is true.

  3. Interface fields are constants (public, static and final), so C is false.

  4. new cannot create an object of an abstract class, so D is false.

CHECK YOURSELF 2One or more options are correct

With the chapter's classes, Shape s = new Square(2); is declared. Taking each line on its own, which of these lines compile?

  1. (A)

    Square q = s;

  2. (B)

    Square q = (Square) s;

  3. (C)

    double a = s.area();

  4. (D)

    double x = s.side;

Answer and solution

Answer: (B), (C)

  1. A needs a written cast: a downcast is never automatic.

  2. B has the cast, so it compiles (and succeeds, since the object is a Square).

  3. C compiles because the declared type Shape has area().

  4. D fails because the declared type Shape has no field side.

CHECK YOURSELF 3

With Shape, Square and Circle as in the chapter (Circle area is 3 r r), Shape[] a = { new Square(2), new Square(3), new Circle(1) }; is built. A loop for (Shape x : a) adds x.area() into a double total that starts at 0. What is total?

Answer and solution

Answer:

  1. Each call dispatches on the actual class of the element.

  2. Square(2) gives 2 × 2 = 4.

  3. Square(3) gives 3 × 3 = 9.

  4. Circle(1) gives 3 × 1 × 1 = 3.

  5. 0 + 4 + 9 + 3 = 16.

CHECK YOURSELF 4

Interfaces Greeter and Welcomer do not extend each other; each declares a default String hello(), returning "hi" and "welcome". Class Base declares public String hello() { return "base"; }. Class Host extends Base, implements both interfaces and does not define hello. What does new Host().hello() return?

  1. (A)

    "hi"

  2. (B)

    "welcome"

  3. (C)

    "base"

  4. (D)

    Nothing: Host does not compile

Answer and solution

Answer: (C)

  1. Host inherits a public hello() from its superclass Base.

  2. That method takes priority over defaults with the same signature, so the defaults do not conflict and no override is needed.

  3. Host compiles, and the call runs Base's body: "base".