Tutorials / Java: From Zero to Advanced / Classes, objects and encapsulation

Classes, objects and encapsulation

15 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

What a class is

A class is a blueprint, and an object is one thing built from it. A BankAccount class describes what every account has (an owner and a balance) and what every account can do (deposit, withdraw). Each account you create with new is an object with its own owner and balance.

Object-oriented design is about putting data and the code that works on it together, and then hiding the details. This hiding is called encapsulation. Other code uses the public methods and cannot reach inside to break the rules.

A complete example

Normally each class has its own file. To keep the example in one file, I declare the class as a nested static class inside Main. In a real project, you would move BankAccount into BankAccount.java.

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {
        BankAccount ayesha = new BankAccount("Ayesha", new BigDecimal("1000"));
        BankAccount bilal = new BankAccount("Bilal");

        ayesha.deposit(new BigDecimal("250.50"));
        ayesha.transferTo(bilal, new BigDecimal("400"));

        System.out.println(ayesha);
        System.out.println(bilal);
        System.out.println("Accounts created: " + BankAccount.getCount());

        try {
            bilal.withdraw(new BigDecimal("5000"));
        } catch (IllegalStateException e) {
            System.out.println("Refused: " + e.getMessage());
        }

        // Two references to one object
        BankAccount alias = ayesha;
        alias.deposit(BigDecimal.TEN);
        System.out.println(ayesha.getBalance());

        // equals and hashCode
        BankAccount a1 = new BankAccount("Sara");
        BankAccount a2 = new BankAccount("Sara");
        System.out.println(a1.equals(a2));                 // false: ids differ
        System.out.println(ayesha.getHistory());
    }

    static class BankAccount {
        private static int count = 0;                  // shared by all accounts

        private final int id;
        private final String owner;
        private BigDecimal balance;
        private final List<String> history = new ArrayList<>();

        BankAccount(String owner) {
            this(owner, BigDecimal.ZERO);              // call the other constructor
        }

        BankAccount(String owner, BigDecimal openingBalance) {
            if (owner == null || owner.isBlank()) {
                throw new IllegalArgumentException("owner is required");
            }
            this.owner = owner;
            this.balance = openingBalance;
            this.id = ++count;
            history.add("opened with " + openingBalance);
        }

        void deposit(BigDecimal amount) {
            requirePositive(amount);
            balance = balance.add(amount);
            history.add("deposit " + amount);
        }

        void withdraw(BigDecimal amount) {
            requirePositive(amount);
            if (amount.compareTo(balance) > 0) {
                throw new IllegalStateException("insufficient funds");
            }
            balance = balance.subtract(amount);
            history.add("withdraw " + amount);
        }

        void transferTo(BankAccount other, BigDecimal amount) {
            this.withdraw(amount);
            other.deposit(amount);
        }

        private static void requirePositive(BigDecimal amount) {
            if (amount.signum() <= 0) {
                throw new IllegalArgumentException("amount must be positive");
            }
        }

        BigDecimal getBalance() { return balance; }
        String getOwner() { return owner; }
        List<String> getHistory() { return List.copyOf(history); }
        static int getCount() { return count; }

        @Override
        public String toString() {
            return "Account#" + id + "[" + owner + ", " + balance + "]";
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof BankAccount other && id == other.id;
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }
}

Walking through it

The fields are private. Outside code cannot write account.balance = 1000000. It must go through deposit or withdraw, and those enforce the rules: positive amounts, no overdraft. That is the real value of encapsulation. The class guards its own consistency. Fields that never change after construction are marked final, and the compiler enforces it.

A constructor has the name of the class and no return type. It runs when you write new. The class has two constructors. The first calls the second with this(...), which avoids duplicating the validation. Inside a method, this is the current object. We need it in this.owner = owner because the parameter has the same name as the field.

The field count is static. There is exactly one copy for the whole class, shared by all objects. We use it to give each account a number. Static methods like getCount are called on the class, not on an object. Be careful with mutable static state. It is shared everywhere and is not thread-safe, so keep it for simple cases like this lesson.

The getter getHistory returns List.copyOf(history), an unmodifiable copy. If it returned the internal list, a caller could add fake entries and bypass the class. This is called a defensive copy.

toString controls what println prints. Without it you get an unhelpful value like Main$BankAccount@6d06d69c. Always write one for classes you debug.

equals and hashCode

The default equals compares references. If two different objects should count as equal, you must override equals, and you must override hashCode together with it. The rule: if two objects are equal, they must have the same hash code. Hash-based collections such as HashSet and HashMap depend on it. In this example I define equality by the account id. The pattern o instanceof BankAccount other checks the type and creates a variable in one step. For plain data classes, the record type in a later lesson writes all of this for you.

References

The alias variable points to the same object as ayesha. A deposit through one is visible through the other. Assigning an object variable copies the reference, not the object.

Common mistakes

  • Public fields. They cannot be protected later without breaking callers.
  • Overriding equals without hashCode. Objects then misbehave in sets and maps.
  • Returning internal mutable collections from getters.
  • Forgetting new, or using an object variable that is still null.
  • Shadowing a field with a parameter and forgetting this, so the field never gets assigned.

Try it yourself

  1. Write a Book class with title, author and a private flag for whether it is borrowed. Add borrow() and giveBack() methods that enforce the rules.
  2. Add toString, and equals based on title and author.
  3. Create a list of books and print only the ones that are available.
java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {

    public static void main(String[] args) {
        BankAccount ayesha = new BankAccount("Ayesha", new BigDecimal("1000"));
        BankAccount bilal = new BankAccount("Bilal");

        ayesha.deposit(new BigDecimal("250.50"));
        ayesha.transferTo(bilal, new BigDecimal("400"));

        System.out.println(ayesha);
        System.out.println(bilal);
        System.out.println("Accounts created: " + BankAccount.getCount());

        try {
            bilal.withdraw(new BigDecimal("5000"));
        } catch (IllegalStateException e) {
            System.out.println("Refused: " + e.getMessage());
        }

        // Two references to one object
        BankAccount alias = ayesha;
        alias.deposit(BigDecimal.TEN);
        System.out.println(ayesha.getBalance());

        // equals and hashCode
        BankAccount a1 = new BankAccount("Sara");
        BankAccount a2 = new BankAccount("Sara");
        System.out.println(a1.equals(a2));                 // false: ids differ
        System.out.println(ayesha.getHistory());
    }

    static class BankAccount {
        private static int count = 0;                  // shared by all accounts

        private final int id;
        private final String owner;
        private BigDecimal balance;
        private final List<String> history = new ArrayList<>();

        BankAccount(String owner) {
            this(owner, BigDecimal.ZERO);              // call the other constructor
        }

        BankAccount(String owner, BigDecimal openingBalance) {
            if (owner == null || owner.isBlank()) {
                throw new IllegalArgumentException("owner is required");
            }
            this.owner = owner;
            this.balance = openingBalance;
            this.id = ++count;
            history.add("opened with " + openingBalance);
        }

        void deposit(BigDecimal amount) {
            requirePositive(amount);
            balance = balance.add(amount);
            history.add("deposit " + amount);
        }

        void withdraw(BigDecimal amount) {
            requirePositive(amount);
            if (amount.compareTo(balance) > 0) {
                throw new IllegalStateException("insufficient funds");
            }
            balance = balance.subtract(amount);
            history.add("withdraw " + amount);
        }

        void transferTo(BankAccount other, BigDecimal amount) {
            this.withdraw(amount);
            other.deposit(amount);
        }

        private static void requirePositive(BigDecimal amount) {
            if (amount.signum() <= 0) {
                throw new IllegalArgumentException("amount must be positive");
            }
        }

        BigDecimal getBalance() { return balance; }
        String getOwner() { return owner; }
        List<String> getHistory() { return List.copyOf(history); }
        static int getCount() { return count; }

        @Override
        public String toString() {
            return "Account#" + id + "[" + owner + ", " + balance + "]";
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof BankAccount other && id == other.id;
        }

        @Override
        public int hashCode() {
            return Objects.hash(id);
        }
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account