OOP in Java

Classes, constructors, static vs instance members, inheritance, abstract classes, interfaces with default methods, records, enums, sealed types, nested classes, and the equals/hashCode contract.

Beginner 3 min readLesson 2 of 14 Interview Q&A

Java is object-oriented to its core: all code lives in classes. This lesson covers the Java-specific mechanics; the design principles are in OOP fundamentals.

Classes, fields and constructors

Java
public class BankAccount {
    private static int nextId = 1;            // shared by all instances
    private final int id;                     // per instance; final = set once
    private final String owner;
    private long balanceCents;

    public BankAccount(String owner) {
        this(owner, 0);                       // delegate to another constructor
    }
    public BankAccount(String owner, long initialCents) {
        if (initialCents < 0) throw new IllegalArgumentException("negative");
        this.id = nextId++;
        this.owner = Objects.requireNonNull(owner);
        this.balanceCents = initialCents;
    }

    public void deposit(long cents) { balanceCents += cents; }
    public long getBalanceCents() { return balanceCents; }

    public static int accountsCreated() { return nextId - 1; }   // no 'this' in static methods
}
  • If you define no constructor, Java provides a no-argument default one.
  • Initialisation order: static fields/blocks (once, when the class loads) → instance fields/initialiser blocks → constructor body.
  • this refers to the current object; super to the parent's members/constructor.

Inheritance

Java
public class SavingsAccount extends BankAccount {
    private final double rate;

    public SavingsAccount(String owner, double rate) {
        super(owner);                          // must be the first statement
        this.rate = rate;
    }

    public void addInterest() { deposit(Math.round(getBalanceCents() * rate)); }

    @Override                                   // compiler checks it really overrides
    public String toString() { return "Savings(" + getBalanceCents() + ")"; }
}
  • Single inheritance of classes; every class ultimately extends Object.
  • final class can't be extended (String); final methods can't be overridden.
  • Overriding rules: same signature; return type may be a subtype (covariant); access can't be narrowed; can't throw broader checked exceptions.
  • Static methods are hidden, not overridden — they don't participate in polymorphism.
  • Fields are not polymorphic either: field access uses the compile-time type.

Abstract classes and interfaces

Java
public abstract class Shape {
    public abstract double area();                     // no body
    public String describe() { return "Area: " + area(); }
}

public interface Drawable {
    void draw(Canvas c);                               // implicitly public abstract
    default void drawTwice(Canvas c) { draw(c); draw(c); }   // Java 8+ default method
    static Drawable empty() { return c -> {}; }               // static factory
}

public class Circle extends Shape implements Drawable, Comparable<Circle> {
    private final double r;
    public Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
    public void draw(Canvas c) { c.circle(r); }
    public int compareTo(Circle o) { return Double.compare(r, o.r); }
}

An interface with exactly one abstract method is a functional interface and can be implemented by a lambda (Streams & lambdas).

If two interfaces provide the same default method, the class must override it and choose: Drawable.super.drawTwice(c).

Records (Java 16+)

Immutable data carriers with constructor, accessors, equals, hashCode and toString generated:

Java
public record Point(int x, int y) {
    public Point {                                     // compact constructor for validation
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
    }
    public double distanceTo(Point o) { return Math.hypot(x - o.x, y - o.y); }
}

var p = new Point(3, 4);
p.x();                         // 3 (accessor, not getX())
p.equals(new Point(3, 4));     // true

Use records for DTOs, value objects, map keys and multiple return values.

Enums

Enums are full classes with a fixed set of instances — they can have fields, constructors and methods:

Java
public enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    EARTH(5.976e+24, 6.37814e6);

    private final double mass, radius;
    Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }
    public double surfaceGravity() { return 6.67300E-11 * mass / (radius * radius); }
}

Planet.valueOf("EARTH");               // from a string
Planet.values();                       // all constants
EnumMap<Planet, Integer> visits = new EnumMap<>(Planet.class);   // very fast map keyed by enum

Sealed types (Java 17+)

Restrict which classes may extend a type. Combined with records and pattern matching, they model algebraic data types with compiler-checked exhaustiveness:

Java
public sealed interface Shape permits Circle, Square, Rect {}
public record Circle(double r) implements Shape {}
public record Square(double side) implements Shape {}
public record Rect(double w, double h) implements Shape {}

static double area(Shape s) {
    return switch (s) {                         // no default needed: compiler knows all cases
        case Circle c -> Math.PI * c.r() * c.r();
        case Square q -> q.side() * q.side();
        case Rect(double w, double h) -> w * h; // record deconstruction pattern (Java 21)
    };
}

Nested classes

KindDeclaredHas access to outer instance?Use
Static nestedstatic class Node inside a classNoHelpers tightly tied to the outer class (Map.Entry, builders)
Innerclass Itr (non-static)Yes — holds a hidden reference to the outer objectIterators
LocalInside a methodYes, plus effectively-final localsRare
Anonymousnew Runnable() { ... }YesMostly replaced by lambdas

The Object methods: equals, hashCode, toString

The contract: if a.equals(b) then a.hashCode() == b.hashCode(). Break it and objects vanish inside HashMap/HashSet.

Java
public final class Email {
    private final String value;
    public Email(String value) { this.value = value.toLowerCase(); }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Email other)) return false;     // pattern matching instanceof
        return value.equals(other.value);
    }
    @Override public int hashCode() { return value.hashCode(); }
    @Override public String toString() { return value; }
}

equals must be reflexive, symmetric, transitive, consistent, and return false for null. Don't use mutable fields in hashCode for objects stored in hash collections. Records generate correct implementations for you.

Key takeaways
  • Constructors validate and initialise; static members belong to the class.
  • Single class inheritance; interfaces with default methods for multiple capabilities.
  • Records for immutable data; enums are full classes; sealed types + switch give exhaustive matching.
  • Prefer static nested classes; inner classes hold the outer instance.
  • Override equals and hashCode together, using the same fields.
Interview questions
QWhat happens if you override equals but not hashCode?medium

Two equal objects will usually have different hash codes (from Object's identity-based hashCode), so hash-based collections put them in different buckets: a HashSet can contain "duplicates" and map.get(equalKey) returns null. The contract requires equal objects to have equal hash codes.

QAbstract class vs interface in modern Java?medium

Interfaces can have default, static and private methods but no instance state or constructors, and a class can implement many. Abstract classes can hold state, constructors and protected members, but a class extends only one. Use interfaces for capabilities and APIs; abstract classes for sharing implementation among closely related types.