LearnFrenzy
Sign in Take a free test

Java Programming · Topic 11 of 28

Encapsulation

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Encapsulation · Study material

Encapsulation is the OOP principle of bundling data with the methods that work on it and hiding the data from the outside world. In Java you make fields private and offer public methods – getters, setters and meaningful operations such as deposit() – so the class itself decides what is allowed. A bank account that exposes public double balance can be set to −50,000 by any line of code; an encapsulated account checks every withdrawal. Encapsulation keeps objects valid, lets you change a class's internals without breaking its users, and makes bugs easier to find because state can change in only a few places. It is one of the four pillars of OOP and a guaranteed interview topic. This page covers getters and setters, validation and invariants, read-only properties, defensive copies, immutability and "tell, don't ask", with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.

On this page

  • Why encapsulation matters
  • Private fields, getters and setters, naming conventions
  • Validation, invariants and read-only or derived properties
  • Leaking references and defensive copies
  • Tell, don't ask; hiding state transitions
  • Encapsulation vs abstraction; immutability

Why encapsulation?

class OpenAccount {                  // ✘ no encapsulation: anyone can break the object
    public double balance;
}

class Account {                      // ✔ encapsulated: the class protects its own rules
    private double balance;

    public double getBalance() { return balance; }

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

    public void withdraw(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("withdrawal must be positive");
        if (amount > balance) throw new IllegalStateException("insufficient funds");
        balance -= amount;
    }
}

public class Main {
    public static void main(String[] args) {
        OpenAccount bad = new OpenAccount();
        bad.balance = -50000;                        // nothing stops this
        System.out.println("open account: " + bad.balance);

        Account good = new Account();
        good.deposit(1000);
        try {
            good.withdraw(5000);
        } catch (IllegalStateException e) {
            System.out.println("rejected: " + e.getMessage());
        }
        System.out.println("encapsulated account: " + good.getBalance());
    }
}

Output

open account: -50000.0
rejected: insufficient funds
encapsulated account: 1000.0

With public fields, the rules ("balance never goes negative") live in every piece of code that touches the field – or nowhere. With private fields, they live in one place, and the object can never be put into an invalid state.

Getters and setters

The JavaBeans convention names accessors getX() / setX(value), and isX() for booleans. Frameworks such as Spring, Hibernate and Jackson rely on these names. A setter is the place to validate and normalise input; the constructor can call the setters to reuse that logic. But do not add a setter for every field automatically – only for values that genuinely may change.

class Employee {
    private String name;
    private int age;
    private double salary;
    private boolean active = true;

    public Employee(String name, int age, double salary) {
        setName(name);                    // reuse the setters' validation
        setAge(age);
        setSalary(salary);
    }

    public String getName() { return name; }
    public void setName(String name) {
        if (name == null || name.isBlank()) throw new IllegalArgumentException("name required");
        this.name = name.strip();
    }

    public int getAge() { return age; }
    public void setAge(int age) {
        if (age < 18 || age > 70) throw new IllegalArgumentException("age 18-70");
        this.age = age;
    }

    public double getSalary() { return salary; }
    public void setSalary(double salary) {
        if (salary < 0) throw new IllegalArgumentException("salary cannot be negative");
        this.salary = salary;
    }

    public boolean isActive() { return active; }      // boolean getters start with "is"
    public void deactivate() { active = false; }       // a meaningful operation instead of setActive(false)
}

public class Main {
    public static void main(String[] args) {
        Employee e = new Employee("  Asha  ", 29, 65000);
        try {
            e.setAge(15);
        } catch (IllegalArgumentException ex) {
            System.out.println("rejected: " + ex.getMessage());
        }
        e.deactivate();
        System.out.println(e.getName() + " " + e.getAge() + " " + e.getSalary() + " " + e.isActive());
    }
}

Output

rejected: age 18-70
Asha 29 65000.0 false

Read-only, write-only and derived properties

A field with a getter but no setter (ideally final) is read-only. A "property" need not be a field at all: getAge() can be calculated from the birth date, so it can never be out of date.

import java.time.LocalDate;
import java.time.Period;

class Person {
    private final String id;                 // read-only: getter, no setter
    private final LocalDate birthDate;
    private String email;                    // read-write

    Person(String id, LocalDate birthDate, String email) {
        this.id = id;
        this.birthDate = birthDate;
        setEmail(email);
    }

    public String getId() { return id; }
    public LocalDate getBirthDate() { return birthDate; }   // LocalDate is immutable, so it is safe to return

    public int getAge(LocalDate today) { return Period.between(birthDate, today).getYears(); }   // derived: no field at all

    public String getEmail() { return email; }
    public void setEmail(String email) {
        if (email == null || !email.matches("[^@\\s]+@[^@\\s]+\\.[a-z]{2,}")) throw new IllegalArgumentException("bad email: " + email);
        this.email = email.toLowerCase();
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("P-7", LocalDate.of(2000, 3, 15), "Asha@Mail.com");
        System.out.println(p.getId() + " " + p.getEmail() + " age " + p.getAge(LocalDate.of(2026, 11, 12)));
        try {
            p.setEmail("not-an-email");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

P-7 asha@mail.com age 26
bad email: not-an-email

Leaking references: defensive copies

Making a field private is not enough if it refers to a mutable object (a list, an array, a java.util.Date). If the constructor stores the caller's object, or the getter returns the internal one, outside code can still change your state. Copy mutable objects on the way in and on the way out – or return an unmodifiable copy.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class LeakyCourse {
    private final List<String> students;
    LeakyCourse(List<String> students) { this.students = students; }     // ✘ stores the caller's list
    List<String> getStudents() { return students; }                       // ✘ hands out the internal list
}

class SafeCourse {
    private final List<String> students;
    private final int[] scores;

    SafeCourse(List<String> students, int[] scores) {
        this.students = new ArrayList<>(students);    // ✔ copy in
        this.scores = scores.clone();
    }
    List<String> getStudents() { return List.copyOf(students); }   // ✔ copy (unmodifiable) out
    int[] getScores() { return scores.clone(); }
}

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Asha", "Ravi"));
        int[] marks = {80, 90};

        LeakyCourse leaky = new LeakyCourse(names);
        SafeCourse safe = new SafeCourse(names, marks);

        names.add("Intruder");                // the caller changes its own list ...
        leaky.getStudents().clear();          // ... or the list it was given back
        marks[0] = 0;
        safe.getScores()[1] = 0;

        System.out.println("leaky: " + leaky.getStudents());
        System.out.println("safe:  " + safe.getStudents() + " " + Arrays.toString(safe.getScores()));
    }
}

Output

leaky: []
safe:  [Asha, Ravi] [80, 90]

Tell, don't ask

Instead of asking an object for its data and making decisions outside it, tell the object what to do and let it apply its own rules. This keeps behaviour next to the data it uses.

import java.util.ArrayList;
import java.util.List;

class Cart {
    private final List<Double> prices = new ArrayList<>();
    private String coupon;

    // Tell the object what to do; it keeps its rules inside
    public void add(double price) { if (price > 0) prices.add(price); }
    public void applyCoupon(String code) {
        if (!"SAVE10".equals(code)) throw new IllegalArgumentException("invalid coupon");
        coupon = code;
    }

    public double total() {
        double sum = 0;
        for (double p : prices) sum += p;
        if (coupon != null) sum *= 0.9;
        return Math.round(sum * 100) / 100.0;
    }

    public int itemCount() { return prices.size(); }
}

public class Main {
    public static void main(String[] args) {
        Cart cart = new Cart();
        cart.add(499);
        cart.add(1299);
        cart.add(-5);              // ignored by the cart's own rule
        cart.applyCoupon("SAVE10");
        // ✘ "Ask" style would be: get the list, loop over it here, apply the discount here – logic leaks out
        System.out.println(cart.itemCount() + " items, total " + cart.total());
    }
}

Output

2 items, total 1618.2

Hiding state transitions

When an object moves through stages (an order, a ticket, a payment), keep the status private and expose only the allowed actions. A setStatus(...) method would let anyone jump from CREATED straight to DELIVERED.

class Order {
    private enum Status { CREATED, PAID, SHIPPED, DELIVERED, CANCELLED }

    private Status status = Status.CREATED;      // only this class can move the status

    public void pay()     { move(Status.CREATED, Status.PAID); }
    public void ship()    { move(Status.PAID, Status.SHIPPED); }
    public void deliver() { move(Status.SHIPPED, Status.DELIVERED); }
    public void cancel() {
        if (status == Status.SHIPPED || status == Status.DELIVERED) throw new IllegalStateException("too late to cancel");
        status = Status.CANCELLED;
    }

    public String status() { return status.name(); }

    private void move(Status from, Status to) {
        if (status != from) throw new IllegalStateException("cannot go " + status + " -> " + to);
        status = to;
    }
}

public class Main {
    static String attempt(Runnable r) {
        try { r.run(); return "ok"; } catch (IllegalStateException e) { return e.getMessage(); }
    }

    public static void main(String[] args) {
        Order o = new Order();
        System.out.println(attempt(o::ship));
        System.out.println(attempt(o::pay) + " " + attempt(o::ship) + " " + o.status());
        System.out.println(attempt(o::cancel) + " " + attempt(o::deliver) + " " + o.status());
    }
}

Output

cannot go CREATED -> SHIPPED
ok ok SHIPPED
too late to cancel ok DELIVERED

Encapsulation vs abstraction

EncapsulationAbstraction
Focushiding the data and implementation inside a classhiding complexity behind a simple interface
Achieved withprivate fields, access modifiers, getters/settersabstract classes, interfaces
Question it answers"How do I protect this object's state?""What should users of this type need to know?"

Common mistakes

  • Public fields "for convenience".
  • Generating a getter and setter for every field – that is just a public field with extra steps.
  • Setters without validation.
  • Returning internal lists or arrays – callers can modify them.
  • Storing the caller's mutable object without copying it.
  • setStatus()-style methods that let callers skip business rules.
  • Separate setters that must be called together (setMin / setMax) – break the invariant in between.

Key points to remember

  • Encapsulation = private data + public behaviour.
  • Validate in setters and constructors; keep invariants true after every public method.
  • Use getX / setX / isX names; add setters only where change is allowed.
  • Copy mutable objects in and out, or expose unmodifiable views.
  • Prefer meaningful operations (deposit, ship) over raw setters.
  • Immutable objects are the strongest form of encapsulation.

Frequently asked questions

Is a class with private fields and public getters/setters for all of them encapsulated?

Only formally. Real encapsulation means the class controls its state – validating changes, hiding fields that need no outside access and offering operations rather than raw setters.

Do getters and setters slow the program down?

No; the JIT compiler inlines such small methods.

What about records?

Records (covered later) are immutable data carriers with private final fields and accessor methods generated automatically.

Where can I learn more?

Read Java Encapsulation and Java OOP Concepts, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links