Skip to content
Visual explainer 8h to learn 6 steps

OOP: classes, interfaces, inheritance, composition

Model a domain with classes and interfaces, and know when to prefer composition.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 2 of 29

In short

Object-oriented Java models a domain as classes that bundle state and behaviour. Interfaces define what an object can do, and polymorphism lets one call work on many types.

Think of it like this: An interface is a job description; each class is a person who does the job their own way.

Explained simply

A class is a blueprint. It says what data an object holds (fields) and what it can do (methods). When you write new BankAccount(), Java builds one object from that blueprint. You can make thousands of objects from one class, and each keeps its own data.

Encapsulation means an object guards its own data. You make fields private and offer methods like deposit() that check the rules first. Then no other code can set the balance to minus one million by accident. The object stays valid all the time.

An interface is a promise: any class that implements it must provide certain methods. Code that only depends on the interface works with every class that keeps the promise. This is polymorphism: the same call, many behaviours.

Inheritance lets one class extend another and reuse its code. It is powerful but ties the two classes tightly together. Composition, where an object simply holds other objects and asks them to do work, is usually more flexible. Most modern Java code uses small interfaces plus composition, and inheritance only for true is-a cases.

Press Play on a diagram to walk through it one step at a time.

MapOne interface, many implementations
interface Shape { area() }
  • class Circle
    • field: radius
    • area = pi * r * r
  • class Square
    • field: side
    • area = side * side
  • class Triangle
    • fields: base, height
    • area = base * height / 2
CompareInheritance vs composition
Inheritance (is-a)
  • class Dog extends Animal
  • Reuses parent code directly
  • Tight coupling to parent internals
  • Only one superclass allowed
Composition (has-a)
  • class Car has an Engine
  • Delegates work to a field
  • Swap parts without changing callers
  • Usually the safer default
SequenceComposition: a Car delegates to its Engine
Driver code
Car
Engine
  1. 1car.start()
    Driver code to Car: car.start()
  2. 2engine.ignite()
    Car to Engine: engine.ignite()
  3. 3running
    Engine to Car: running
  4. 4started
    Car to Driver code: started

In depth

Constructors, this and static

A constructor runs when you call new and must leave the object in a valid state. If you write no constructor, Java adds an empty one with no parameters. As soon as you write any constructor, that free one disappears. One constructor can call another with this(...), which avoids repeating code, and a subclass constructor calls its parent with super(...) on its first line.

Mark fields final when they should never change after construction; the compiler then insists that every constructor sets them. Fields and methods marked static belong to the class itself, not to any one object. A static counter is shared by all objects, and a static method cannot read instance fields because there is no this.

  • Fields get default values: 0, false or null
  • Validate arguments in the constructor and throw early
  • Static factory methods like Money.of(...) can have clear names

Access modifiers from closed to open

Java has four access levels. private means only code inside the same class can see the member. With no keyword at all you get package-private: any class in the same package can see it, which is handy for tests and helpers. protected adds subclasses in other packages. public means everyone.

A good default is: fields private, methods as closed as possible, and only the real API public. Getters are not automatically good. Adding getX and setX for every field just moves the rules out of the object. Prefer methods that express intent, like account.withdraw(50), over setBalance(balance - 50) written by the caller.

LayersWho can see a member
  1. 1
    public

    Any class, in any package

  2. 2
    protected

    Same package, plus subclasses anywhere

  3. 3
    package-private (no keyword)

    Only classes in the same package

  4. 4
    private

    Only code inside the same class

Interfaces vs abstract classes today

Since Java 8 an interface can contain default methods (with a body) and static methods, and since Java 9 private helper methods too. What it cannot hold is instance state: any fields are automatically public static final constants. A class can implement many interfaces but extend only one class.

An abstract class can have constructors, protected fields and partly finished logic, and it cannot be created with new. Use it when several closely related classes share real state and code, such as a template where subclasses fill in one step. Use an interface to describe a capability that unrelated classes may offer, like Comparable or Runnable. When in doubt, start with an interface; you can add a small abstract base class behind it later.

  • interface: many per class, no instance fields
  • abstract class: one parent, can hold state
  • default methods let you add to an interface without breaking implementers

How polymorphism really works

When you call shape.area(), the JVM looks at the actual object at run time and runs that class's version. This is called dynamic dispatch, and it is why a List of Shape can hold circles and squares that each compute their own area. Always add @Override on overriding methods: if you misspell the name or get a parameter type wrong, the compiler tells you instead of silently creating a new method.

Overloading is different. Methods with the same name but different parameters are chosen at compile time, using the declared types of the arguments. Static methods and fields are not polymorphic either: a static method in a subclass hides the parent one, and the choice depends on the declared type, not the object.

The equals and hashCode contract

By default equals() means same object, which is rarely what you want for value-like classes such as Money or Email. If you override equals, the rules are: an object equals itself, a.equals(b) matches b.equals(a), equality is transitive, and the answer does not change over time. And equal objects must return the same hashCode().

HashMap and HashSet first use hashCode() to pick a bucket and only then call equals() inside it. If two equal objects have different hash codes, they land in different buckets and contains() returns false. Build both methods from the same fields, using Objects.equals and Objects.hash, or let your IDE or a record generate them. Avoid mutable fields in them: if a field changes while the object is inside a HashSet, it gets lost.

FlowWhat set.contains(x) does
  1. Step 1
    x.hashCode()

    Turn the object into an int

  2. Step 2
    Pick bucket

    The hash decides which bucket to search

  3. Step 3
    Compare in bucket

    Call equals() on each entry there

  4. Step 4
    Answer

    true only if equals() matched in that bucket

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Write classes, fields and constructors~1h 20m
  2. 2
    Encapsulate state with access modifiers~1h 20m
  3. 3
    Use interfaces and abstract classes~1h 20m
  4. 4
    Apply inheritance and polymorphism~1h 20m
  5. 5
    Prefer composition over inheritance~1h 20m
  6. 6
    Implement equals, hashCode and toString~1h 20m

Key points

  • Keep fields private and expose behaviour through methods (encapsulation).
  • Program to interfaces so callers do not depend on concrete classes.
  • Prefer composition; use inheritance only for a true is-a relationship.
  • If you override equals, also override hashCode, or HashMap and HashSet break.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
interface Shape { double area(); }

class Circle implements Shape {
  private final double r;
  Circle(double r) { this.r = r; }
  public double area() { return Math.PI * r * r; }
}

class Square implements Shape {
  private final double side;
  Square(double side) { this.side = side; }
  public double area() { return side * side; }
}

// Polymorphism: for (Shape s : List.of(new Circle(1), new Square(2))) s.area();

Callers only know Shape, so new shapes need no caller changes.

Encapsulating a bank account

Requirement: the balance can never go negative. Step 1: make the balance private so nothing outside can write to it. Step 2: offer deposit and withdraw methods that check the rule before changing state. Step 3: expose a read-only getter. Now every BankAccount object is always valid, and the rule lives in exactly one place instead of in every caller.

java
public class BankAccount {
  private final String owner;
  private long balanceCents;
  public BankAccount(String owner) { this.owner = owner; }
  public void deposit(long cents) {
    if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
    balanceCents += cents;
  }
  public void withdraw(long cents) {
    if (cents > balanceCents) throw new IllegalStateException("insufficient funds");
    balanceCents -= cents;
  }
  public long balanceCents() { return balanceCents; }
}

When inheritance breaks: counting adds in a HashSet

You want a set that counts how many elements were ever added. Extending HashSet and overriding both add and addAll looks natural, but addAll in the parent calls add for each element, so every element is counted twice. Your class depends on hidden details of its parent. The fix is composition: wrap a Set in a field, implement the counting yourself and delegate the real work. The wrapper no longer cares how the inner set is built.

java
class CountingSet<E> {
  private final Set<E> inner = new HashSet<>();
  private int addCount = 0;

  public boolean add(E e) { addCount++; return inner.add(e); }

  public boolean addAll(Collection<? extends E> c) {
    addCount += c.size();
    return inner.addAll(c);   // inner's internals no longer matter
  }

  public int addCount() { return addCount; }
  public boolean contains(Object o) { return inner.contains(o); }
}

Quick reference

  • Fields private, methods as closed as possible, only the real API public
  • Writing any constructor removes the free no-argument constructor
  • Put @Override on every overriding method so typos become compile errors
  • Override equals and hashCode together, built from the same fields
  • Overloading is chosen at compile time; overriding is chosen at run time
  • A class extends one class but can implement many interfaces
  • Prefer composition (has-a) unless the subclass truly is-a parent

Common mistakes

  • Making every field public, so any code can break the object's rules.
  • Building deep inheritance chains where a small interface would do.
  • Overriding equals without hashCode.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A class has fields but you wrote only Person(String name). What happens with new Person()?

Question 2

2Which access level lets classes in the same package see a member, but not subclasses in other packages?

Question 3

3Two Point objects are equal by equals() but have different hashCode() values. What breaks?

Question 4

4What can an abstract class have that an interface cannot?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a class Temperature with a private double celsius, a constructor that rejects values below -273.15, and a method toFahrenheit().

  2. Exercise 2medium

    Define an interface Discount with double apply(double price). Write two implementations, PercentOff and FixedOff, and a Checkout class that receives a Discount in its constructor.

  3. Exercise 3hard

    Write a class Email that stores an address and implements equals, hashCode and toString so that "A@x.com" and "a@x.com" are equal. Prove it works in a HashSet.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should every field have a getter and a setter?
No. Add only what callers really need. Setters for everything break encapsulation, because the rules then live in every caller instead of in the class.
Why does Java not allow extending two classes?
Multiple inheritance of state causes conflicts when both parents define the same field or method. Java allows many interfaces instead, and resolves default method clashes by forcing you to override.
When should I use an abstract class instead of an interface?
When several closely related classes share real fields and code, such as a template method. For describing what a type can do, prefer an interface.
Is a record a replacement for classes?
Records replace simple immutable data classes. Classes with changing state, complex behaviour or inheritance needs are still written as normal classes.

Go deeper

ShareXLinkedInWhatsApp