Skip to the content

Lesson 286 of 296

Java object-oriented programming

What you will learn

  • Classes, fields, constructors and this
  • Access modifiers and encapsulation
  • static and final
  • Inheritance, abstract classes and polymorphism
  • Interfaces
  • Records and enums
  • equals, hashCode and toString
On this page

Classes and constructors

Java
public class Account {
    private final String owner;    // private: only this class can see it
    private double balance;        // final: can be set only once

    public Account(String owner, double balance) {   // constructor
        this.owner = owner;
        this.balance = balance;
    }

    public Account(String owner) {                   // overloaded constructor
        this(owner, 0);
    }

    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        balance += amount;
    }

    public double getBalance() { return balance; }   // a "getter"
    public String getOwner() { return owner; }

    public static void main(String[] args) {
        Account a = new Account("Sam");
        a.deposit(50);
        System.out.println(a.getOwner() + " " + a.getBalance());  // Sam 50.0
    }
}

Access modifiers and encapsulation

ModifierWho can access
publicEveryone
protectedSame package and subclasses
(none, "package-private")Same package only
privateThis class only

Encapsulation: keep fields private and allow changes only through methods that protect the rules (like deposit rejecting negative amounts). Unlike TypeScript, private is enforced at runtime too.

static and final

  • static belongs to the class, not to each object: Math.max(...), a shared counter, a factory method.
  • final variable: cannot be reassigned (like const). final method: cannot be overridden. final class: cannot be extended (String is final).

Inheritance, abstract classes and polymorphism

Java
public class Shapes {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(2) };
        for (Shape s : shapes) {
            System.out.println(s.describe());  // polymorphism: each uses its own area()
        }
    }
}

abstract class Shape {                         // cannot be created directly
    abstract double area();                    // subclasses must implement it

    String describe() {
        return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
    }
}

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

class Square extends Shape {
    private final double side;
    Square(double side) { this.side = side; }
    @Override double area() { return side * side; }
}
  • extends: a class can extend only one class.
  • @Override asks the compiler to check you really are overriding a parent method.
  • super(...) calls the parent constructor; super.method() calls the parent's version.
  • Polymorphism: a Shape variable can hold a Circle or Square, and the right area() runs.

Interfaces

An interface is a contract. A class can implement many interfaces. Unlike TypeScript (structural typing), Java uses nominal typing: a class must say implements explicitly, even if it has the right methods.

Java
public class Interfaces {
    public static void main(String[] args) {
        Invoice inv = new Invoice(120.0);
        Payable p = inv;                      // program to the interface
        System.out.println(p.summary());      // Due: 120.0
        System.out.println(inv.print());      // Invoice for 120.0
    }
}

interface Payable {
    double amountDue();

    default String summary() {               // default method: shared implementation
        return "Due: " + amountDue();
    }
}

interface Printable {
    String print();
}

class Invoice implements Payable, Printable {
    private final double total;
    Invoice(double total) { this.total = total; }
    public double amountDue() { return total; }
    public String print() { return "Invoice for " + total; }
}
Abstract classInterface
Can have fields with state and constructorsNo instance state (constants only)
A class extends only oneA class can implement many
Use for a shared base with shared codeUse for a capability or contract

Records and enums

A record (Java 16+) is a short, immutable data class. Java writes the constructor, getters, equals, hashCode and toString for you.

Java
public class RecordsEnums {
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        System.out.println(a);                       // Point[x=1, y=2]
        System.out.println(a.x());                   // 1  (accessor, not getX())
        System.out.println(a.equals(new Point(1, 2)));  // true
        System.out.println(Status.PAID.isDone());    // false
        System.out.println(Status.valueOf("SHIPPED").ordinal());  // 2
    }
}

record Point(int x, int y) {
    Point {                                   // compact constructor for validation
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
    }
}

enum Status {
    PENDING, PAID, SHIPPED;

    boolean isDone() { return this == SHIPPED; }
}

equals, hashCode and toString

Every class extends Object, which has:

  • toString(): the text form. Override it for readable logs.
  • equals(Object o): are two objects equal in value? By default it checks if they are the same object.
  • hashCode(): a number used by HashMap and HashSet to find objects quickly.

The rule: if you override equals, you must override hashCode, so that equal objects have equal hash codes. Otherwise HashMap and HashSet break.

Java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class Equality {
    public static void main(String[] args) {
        Set<Email> emails = new HashSet<>();
        emails.add(new Email("Sam@Example.com"));
        emails.add(new Email("sam@example.com"));
        System.out.println(emails.size());    // 1, because equals and hashCode agree
    }
}

class Email {
    private final String value;
    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 Objects.hash(value); }
    @Override public String toString() { return value; }
}

Records do this for you, which is one reason to prefer them for data.

How to say it in an interview

"I keep fields private and change them through methods that protect the rules. static belongs to the class, final prevents reassignment, overriding or extending. A class extends one class but implements many interfaces, and Java uses nominal typing, so implements must be explicit. I use abstract classes for a shared base with code, interfaces for contracts, records for immutable data and enums for fixed sets of values. If I override equals I always override hashCode, or hash-based collections break."

Key words

WordMeaning
ConstructorCode that runs when an object is created with new
EncapsulationHiding fields and exposing safe methods
staticBelongs to the class, not each object
finalCannot be reassigned, overridden or extended
PolymorphismOne type of variable, different behaviour per subclass
InterfaceA contract a class promises to fulfil
RecordA short immutable data class
hashCodeA number used to find objects in hash-based collections

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.