Day 19 / 25 Java Inheritance, Interfaces & Polymorphism 0/0 exercises Exercises ↓

AmouAI Hub/Courses/Programming Fundamentals/Day 19

Week 4 · Java: A Second Lens · Day 19

Java Inheritance, Interfaces & Polymorphism

Interfaces are the idea Python never forces you to learn. Here you cannot avoid them — and that turns out to be the point.

Study time
4 hours
Reading
Head First Java, Ch. 7–8
Focus
extends · interfaces · dispatch

By the end of today you can

  1. Write a subclass with extends and override with @Override
  2. Call the parent with super, and say when you must
  3. Declare and implement an interface
  4. Choose between an abstract class and an interface
  5. Explain dynamic dispatch — why the object, not the variable, picks the method
  6. Say what Java gains and loses versus Python's duck typing
  7. Implement multiple interfaces on one class

Today's videos

Watch each video, then work the matching sections below. Watching alone will not do it.

19A
extends, @Override and super (120 min)
Rebuilding Day 14's shapes in Java · abstract classes and abstract methods · the three Day 14 bugs Java catches at compile time · @Override as a typo detector.
19B
Interfaces & Dynamic Dispatch (120 min)
Declaring a contract and being held to it · abstract class versus interface · implementing several · what the variable's type decides versus what the object's type decides · why frequent casting means the design is wrong.

1extends and @Override

Day 14's shapes, rebuilt.

Java catches three of Day 14's bugs at compile time

Forgetting super(...) — compile error. Misspelling an overridden method name — compile error with @Override. Forgetting to implement an abstract method — compile error. In Python all three are runtime failures, and the third might not surface for weeks.

2Interfaces

The contract, written down and enforced.

An interface is a list of method signatures with no bodies. A class that implements it must provide every one, and the compiler checks.

Printable.java
public interface Printable {
    String describe();          // no body — just the promise
    default String shout() {    // interfaces MAY have defaults
        return describe().toUpperCase();
    }
}


public class Invoice implements Printable {
    @Override
    public String describe() {
        return "invoice #4471";
    }
}
Abstract classInterface
A class may haveOne parentMany interfaces
Can hold state (fields)YesNo (only constants)
Can have a constructorYesNo
Says"is a kind of""is capable of"
Reach for it whenSubclasses share code and stateUnrelated classes share a capability
Multiple.java
public class Report implements Printable, Comparable<Report>, Serializable {
    // must implement describe(), compareTo(), and can now be serialised
}
The rule of thumb

If two classes share an identity — a Circle and a Rectangle are both Shapes — use an abstract class. If they share only an ability — a Report and a Contact can both be printed, but are otherwise unrelated — use an interface. Java only lets you inherit once, so save that one slot for the identity.

This is the idea Python never made you learn

3Dynamic dispatch

The variable's type decides what you may call. The object decides what runs.

Dispatch.java
Shape s = new Circle(2);      // variable type Shape, object type Circle

System.out.println(s.area());     // runs Circle's area — the OBJECT decides
System.out.println(s.describe()); // runs Shape's describe

System.out.println(s.getRadius()); // COMPILE ERROR — Shape has no getRadius
Two different questions, answered at two different times

What may I call? Decided at compile time, by the variable's type. What actually runs? Decided at run time, by the object's type. That second half is called dynamic dispatch, and it is what makes polymorphism work in a statically typed language.

The lookup rule is exactly the same as Python's: start at the object's own class and walk up until you find the method. The difference is only that Java checked in advance that you would find one.

Casting, and instanceof

Casting.java
Shape s = new Circle(2);

if (s instanceof Circle c) {   // pattern matching, Java 16+
    System.out.println(c.getRadius());
}
Frequent casting means the design is wrong

If you keep asking "what type is this really?" you have thrown away the benefit of polymorphism and rebuilt the if-chain that Day 14 removed. The whole point is that the loop should not need to know. An occasional cast is fine; a chain of instanceof checks is a design smell.

>_Python playground

A real Python interpreter running inside your browser. Nothing is installed, nothing is uploaded, nothing can break.

scratch.pypython not loaded
Values for input(), comma separated →
Output appears here. The first run takes a few seconds while Python loads.

Exercise set

Checked automatically the moment you submit. Work top to bottom — each one assumes the last. Your answers are saved in this browser.

All Warm-up Core Challenge Reset day

Day 20 — Java Collections, Generics & Mini-Project 4

The same structures as Week 2, now with the type system watching.

Continue →