SyntaxPilot
Courses/Java/Lesson 17
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 17 of 51

Encapsulation, access modifiers, packages

queued

These are the notes for Java episode 17. Episode 16 ended with a hole: any code, anywhere, could write aarav.total = -50 and Java said nothing. Today our objects learn to protect their own data. You will see why public fields and "checking before every assignment" both fail, lock fields with private, give them one safe door with setters and a way to read them with getters, build a bank account that has no setter at all, learn Java's four access levels, and organise classes into packages with import. Every example below was run with javac 21, and its real output or error is shown.

The problem: the marks register left open

Picture a school's marks register lying open on the staff-room desk. Anyone who walks past can write -50, or 500 in a paper out of 100. Nobody checks, and at the end of term the report cards are printed with those numbers.

Our Student class is exactly that register:

class Student {
    String name;
    int marks;
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student();
        a.name = "Aarav";
        a.marks = -50;
        Student d = new Student();
        d.name = "Diya";
        d.marks = 500;
        System.out.println(a.name + ": " + a.marks);
        System.out.println(d.name + ": " + d.marks);
    }
}
Aarav: -50
Diya: 500

This isn't Java's fault: an int can hold -50. Only we know that marks must be between 0 and 100, and we never told the program.

The obvious fix fails: checking before every assignment

The first idea is to check the value wherever marks are set:

class Student {
    String name;
    int marks;
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student();
        a.name = "Aarav";
        int entered = 95;
        if (entered >= 0 && entered <= 100) {
            a.marks = entered;
        }
        // sports bonus, added later by someone else
        a.marks = a.marks + 10;
        System.out.println(a.name + ": " + a.marks);
    }
}
Aarav: 105

The check exists, but only in one place. Months later someone adds a sports bonus somewhere else, doesn't know about the check, and 105 out of 100 gets in.

Why it went wrong

  • The rule lives outside the object, copied into every caller (admission, re-evaluation, bonus...).
  • One caller that forgets the check is enough to let bad data in.
  • The real problem is the field itself: it is open to everyone.
  • The fix: lock the field, and put one check inside the object.

private fields: nobody walks into the bank vault

In a bank In Java
The vault: customers can't walk in private field: no access from outside the class
The cashier checks every request setter method: the only door to the field, with the rule
The passbook: you can read your balance getter method: returns the value, read-only

private is an access modifier: a keyword that controls who may use a field, method or constructor. A private member can be used only by code inside the same class.

class Student {
    String name;
    private int marks;
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student();
        a.name = "Aarav";
        a.marks = -50;
        System.out.println(a.marks);
    }
}
Main.java:10: error: marks has private access in Student
        a.marks = -50;
         ^
Main.java:11: error: marks has private access in Student
        System.out.println(a.marks);
                            ^
2 errors

Both writing and reading are blocked. A compile error is much better than a wrong report card, but now nobody can set marks at all. We need the cashier.

Getters and setters: one door, one rule

A setter is a method that sets a private field, after checking the new value. A getter is a method that returns a private field's value.

class Student {
    private String name;
    private int marks;
    Student(String name) {
        this.name = name;
    }
    void setMarks(int marks) {
        if (marks < 0 || marks > 100) {
            System.out.println("Rejected: " + marks);
            return;
        }
        this.marks = marks;
    }
    int getMarks() {
        return marks;
    }
    String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Student a = new Student("Aarav");
        a.setMarks(95);
        a.setMarks(a.getMarks() + 10);
        a.setMarks(-50);
        System.out.println(a.getName() + ": " + a.getMarks());
    }
}
Rejected: 105
Rejected: -50
Aarav: 95
  • setMarks is the only way to change marks, and every value must pass the check.
  • The sports bonus can no longer go around the rule: it has to call setMarks too, so 105 is rejected.
  • The rule is written once. Anyone who adds a feature next year gets it for free.

Encapsulation

Encapsulation means packing an object's data together with the methods that guard it into one unit (like a medicine capsule), and hiding the data inside. The recipe:

  1. Make fields private.
  2. Give a setter (with the rule) only for fields that may change.
  3. Give a getter for fields others need to read.

Naming conventions: getMarks(), setMarks(int); for a boolean field the getter is usually isPassed().

Is a setter that only does this.marks = marks useful?

A setter with no check still lets you add one later without changing every caller, which is why many teams write them. But don't add getters and setters to every field automatically: give the outside world only what it needs.

A bank account: no setter at all

Encapsulation isn't "a getter and a setter for every field". A bank balance must never be set to any number you like; it changes only through deposits and withdrawals, each with its own rule.

class Account {
    private int balance;
    void deposit(int amount) {
        if (amount <= 0) {
            System.out.println("Invalid amount");
            return;
        }
        balance += amount;
    }
    void withdraw(int amount) {
        if (amount > balance) {
            System.out.println("Not enough balance");
            return;
        }
        balance -= amount;
    }
    int getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(2000);
        acc.withdraw(5000);
        acc.withdraw(500);
        System.out.println("Balance: " + acc.getBalance());
    }
}
Not enough balance
Balance: 1500

Add one line at the end of main, acc.balance = 1000000;, and:

Main.java:29: error: balance has private access in Account
        acc.balance = 1000000;
           ^
1 error

A field with a getter and no setter is read-only from outside. The class decides what the outside world may do.

The four access levels

At home Access level Who can use it
Your diary private Only code in the same class
The family TV (default): no keyword, also called package-private + every class in the same package
The family recipe, passed to your children protected + subclasses (child classes, episode 18), even in other packages
The nameplate on the gate public Everyone, everywhere

From most closed to most open: private → default → protected → public.

Rules of thumb:

  • Fields private; the methods other classes need public. Open things up only when there is a reason.
  • A top-level class (one not inside another class) can only be public or default. private class Student at the top of a file does not compile.
  • A .java file can have at most one public top-level class, and the file must be named after it (Main.java for public class Main).

Packages and import

Two students called Rahul in one school: when the principal calls "Rahul!", both stand up. So the school says "Rahul of 10-A": the section becomes part of the name. Sections also keep a big school organised.

A package is Java's section: a named group of related classes, stored as a folder. A class's full name (its fully qualified name) includes its package: java.util.Arrays, java.util.Scanner, school.Student.

import

public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 95, 48};
        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));
    }
}
Main.java:4: error: cannot find symbol
        Arrays.sort(marks);
        ^
  symbol:   variable Arrays
  location: class Main
Main.java:5: error: cannot find symbol
        System.out.println(Arrays.toString(marks));
                           ^
  symbol:   variable Arrays
  location: class Main
2 errors

Arrays lives in the package java.util. An import statement at the top of the file tells the compiler which one we mean:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 95, 48};
        Arrays.sort(marks);
        System.out.println(Arrays.toString(marks));
    }
}
[48, 72, 95]
  • import java.util.*; imports every class of java.util (not its sub-packages).
  • Without any import you can always write the full name: java.util.Arrays.sort(marks);
  • java.lang (String, System, Math, Integer...) is imported automatically. That's why String never needed an import.

Your own packages

The first line of a file says which package its classes belong to, and the file sits in a folder with the same name.

school/Student.java:

package school;

public class Student {
    private int marks;
    String name;
    public String getName() {
        return name;
    }
}

app/Main.java:

package app;

import school.Student;

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.getName());
        s.name = "Aarav";
    }
}

Compiling both from the folder that contains school and app:

$ javac -d out school/Student.java app/Main.java
app/Main.java:9: error: name is not public in Student; cannot be accessed from outside package
        s.name = "Aarav";
         ^
1 error

name has default access: usable inside package school, but app is a different package. Remove line 9 and it compiles and runs (java -cp out app.Main), printing null, because getName() is public and nobody set a name.

A class without public can't even be imported from another package:

app/Main.java:3: error: Teacher is not public in school; cannot be accessed from outside package
import school.Teacher;
             ^
1 error

Two classes with the same simple name can live in different packages. Use their full names to tell them apart:

school.Student a = new school.Student();
hostel.Student b = new hostel.Student();

Package names are written in lowercase, and real projects often start with a reversed domain name: in.syntaxpilot.school.

In the single-file programs we've written so far, every class is in the same default (unnamed) package, which is why classes without public worked fine together.

What you just invented

Problem Fix
Anyone can write -50 into a field private: lock the field
Checks copied into every caller, one forgets A setter: one door, one rule, inside the object
Others still need to read the value A getter
Some values must never be set freely No setter, only meaningful methods (deposit, withdraw)
Thousands of classes, clashing names Packages, full names and import

Together that's encapsulation: the object guards its own data.

The next problem: the school needs a Teacher class. A teacher has a name, a phone and an address, and needs the same setPhone check as Student. Copy-pasting half of Student into Teacher means every fix must be made twice. Episode 18 fixes that with inheritance.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
a.marks = -50; when marks is private error: marks has private access in Student Only code inside Student may use it a.setMarks(...), a.getMarks()
Arrays.sort(marks); with no import error: cannot find symbol / symbol: variable Arrays Arrays lives in java.util import java.util.Arrays;
s.name = "Aarav"; from another package error: name is not public in Student; cannot be accessed from outside package Default access = same package only Use a public method, or make it public
import school.Teacher; when class Teacher isn't public error: Teacher is not public in school; cannot be accessed from outside package The class has default access public class Teacher
A setter that forgets to check no error The rule is skipped Put the validation inside the setter
marks = marks; inside setMarks(int marks) no error, the field stays 0 The parameter shadows the field this.marks = marks;

Mini project: a phone battery that can't lie

A Phone keeps its battery between 0 and 100. charge adds percent but never goes above 100; use takes percent but refuses to go below 0. There is no setBattery.

class Phone {
    private String model;
    private int battery;
    Phone(String model, int battery) {
        this.model = model;
        if (battery < 0 || battery > 100) {
            battery = 50;
        }
        this.battery = battery;
    }
    void charge(int percent) {
        if (percent <= 0) {
            System.out.println("Invalid charge");
            return;
        }
        battery = Math.min(100, battery + percent);
    }
    void use(int percent) {
        if (percent > battery) {
            System.out.println(model + ": battery too low");
            return;
        }
        battery -= percent;
    }
    int getBattery() {
        return battery;
    }
    boolean isLow() {
        return battery < 20;
    }
}

public class Main {
    public static void main(String[] args) {
        Phone p = new Phone("Pixel", 40);
        p.use(30);
        System.out.println(p.getBattery() + "% low=" + p.isLow());
        p.use(25);
        p.charge(150);
        System.out.println(p.getBattery() + "%");
        p.charge(-5);
    }
}
10% low=true
Pixel: battery too low
100%
Invalid charge

Practice

  1. Make age in Student read-only: set it once in the constructor (reject ages outside 3-25 by using 0), give it a getter and no setter.
  2. Add boolean isPassed() to Student (passed when marks >= 33).
  3. A Wallet with a private balance and a method pay(int amount) that returns true if the payment went through and false otherwise.
  4. Which lines compile? Assume both classes are in the same file:
class Box {
    private int a;
    int b;
    protected int c;
    public int d;
}
// in main of another class in the same file:
Box x = new Box();
x.a = 1;   // line A
x.b = 2;   // line B
x.c = 3;   // line C
x.d = 4;   // line D
Solutions

1 and 2.

class Student {
    private String name;
    private int age;
    private int marks;
    Student(String name, int age) {
        this.name = name;
        if (age < 3 || age > 25) {
            age = 0;
        }
        this.age = age;
    }
    int getAge() {
        return age;
    }
    void setMarks(int marks) {
        if (marks >= 0 && marks <= 100) {
            this.marks = marks;
        }
    }
    boolean isPassed() {
        return marks >= 33;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Diya", 15);
        s.setMarks(41);
        System.out.println(s.getAge() + " " + s.isPassed());
        Student t = new Student("Kabir", 99);
        t.setMarks(20);
        System.out.println(t.getAge() + " " + t.isPassed());
    }
}
15 true
0 false

3.

class Wallet {
    private int balance;
    Wallet(int balance) {
        this.balance = Math.max(0, balance);
    }
    boolean pay(int amount) {
        if (amount <= 0 || amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }
    int getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        Wallet w = new Wallet(300);
        System.out.println(w.pay(120) + " " + w.pay(500) + " " + w.getBalance());
    }
}
true false 180

4. Line A fails (error: a has private access in Box). Lines B, C and D compile: the classes are in the same package, so default and protected members are visible too.

Quick quiz

class Tank {
    private int litres;
    void fill(int l) {
        if (litres + l > 100) {
            System.out.println("Overflow");
            return;
        }
        litres += l;
    }
    int getLitres() { return litres; }
}
// in main:
Tank t = new Tank();
t.fill(60);
t.fill(50);
t.fill(30);
System.out.println(t.getLitres());

A) 140 B) Overflow, then 90 C) Overflow, then 110 D) Compile error

Answer

B. fill(60) stores 60. fill(50) would make 110 > 100, so it prints Overflow and stores nothing. fill(30) makes 90.

Interview questions

  1. What is encapsulation? Bundling data and the methods that operate on it into one class, and hiding the data (private fields) so it can only be changed through controlled methods.
  2. Why make fields private if you add a getter and setter anyway? The setter can validate, log or change its rules later without touching any caller; the getter can return a computed or copied value; and you can decide not to provide a setter at all.
  3. What are the four access levels? private (class), default/package-private (package), protected (package + subclasses), public (everywhere).
  4. Can a top-level class be private or protected? No. Only public or default.
  5. What is a package and why use one? A namespace and folder for related classes: it avoids name clashes, organises code and controls access (default access stops at the package).
  6. Which package is imported automatically? java.lang.
  7. Does import java.util.*; import java.util.function.Function? No. A wildcard import covers one package, not its sub-packages.
  8. Encapsulation vs abstraction? Encapsulation hides data behind methods; abstraction hides complexity behind a simple interface (episodes 20 and 21).

Glossary

Term Meaning Example
Access modifier A keyword that controls who may use a class, field, method or constructor private, public
private Usable only inside the same class private int marks;
Default (package-private) access No keyword: usable by every class in the same package String name;
protected Same package, plus subclasses in other packages protected int rollNo;
public Usable everywhere public String getName()
Encapsulation Data plus the methods that guard it, packed into one object, with the data hidden private fields + setters/getters
Getter A method that returns a field's value int getMarks()
Setter A method that changes a field, after checking the value void setMarks(int marks)
Validation Checking that a value obeys the rules before accepting it if (marks < 0 \|\| marks > 100)
Read-only field A field with a getter and no setter getBalance() only
Package A named group of related classes, stored as a folder java.util, school
Fully qualified name A class's name including its package java.util.Arrays
import Tells the compiler which package a class name comes from import java.util.Arrays;
java.lang The package imported automatically String, System, Math
Default package The unnamed package of a file with no package line our single-file programs
Shadowing A parameter with the same name hides the field marks = marks; does nothing

Summary

  • Public fields accept any value their type allows, even -50 marks.
  • Checking in every caller fails: one caller always forgets.
  • private locks a field inside its class: marks has private access in Student.
  • A setter is the one door in, with the rule; a getter reads the value. Some fields get no setter at all.
  • Encapsulation = the object guards its own data.
  • Access levels: private < default < protected < public. Fields private, needed methods public.
  • Packages group classes in folders and give them full names; import brings a class in; java.lang is automatic.
  • Next: Teacher copy-pastes half of Student. Episode 18: inheritance.