Skip to the page

Object-oriented programming · core

Abstract class, interface, composition and the diamond

Choose between an abstract class and an interface, and between inheritance and composition, by the relationship you need.

The notes

What you must know

  • Abstract class: can have fields, constructors and normal methods along with abstract ones. A class extends only one.
  • Interface: a contract of what a class can do. A class can implement many. Methods can have bodies if they are default or static (Java 8) or private (Java 9).
  • Shape as an abstract class (shared colour field, abstract area()). Printable and Resizable as interfaces for unrelated things.
  • Inheritance is "is a": a Car is a Vehicle. Composition is "has a": a Car has an Engine. Car extends Engine is wrong.
  • Composition with an Engine interface lets you swap engines and test with a fake one. Prefer composition when the relationship is not truly "is a".
  • Aggregation is a loose has-a (a department has professors who still exist if it closes). Composition is a strong has-a: the part lives and dies with the whole.
  • Diamond problem: D extends B and C, which both extend A. Which version of show() does D get? Java allows one parent class, but many interfaces.
  • Two interfaces with the same default method give a compile error until the class overrides it; it can call B.super.show(). C++ allows multiple inheritance and uses virtual inheritance to keep one copy of A.

The red pen

Common traps: mistake → fix

  • Mistake: Interfaces cannot have method bodies

    Fix: default, static and private methods can.

  • Mistake: Abstract classes cannot have constructors

    Fix: they can.

  • Mistake: Always inherit to reuse code

    Fix: use composition when it is not "is a".

  • Mistake: Java supports multiple inheritance with classes

    Fix: only with interfaces.

Easy to hard

Questions interviewers ask, easy to hard

  1. Abstract class or interface: when do you use each?
  2. Car and Engine: inheritance or composition?
  3. What is the diamond problem and how does Java handle it?
  4. What is the difference between aggregation and composition?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview