Chapter 4.2: Encapsulation
Introduction
Learning Outcomes
Show with examples how a class bundles data with the methods that use it, hides internal details (information hiding) and separates “what” from “how”.
State a method's precondition and postcondition in a comment and check them in code.
public, private, protected and package access: use a table to say who can reach each.
Make fields private and write validating accessors; use the this.field = field idiom.
Change a class's internals without changing its outside; meet interface and implements.
package and import: group classes, compile and run them, and resolve class name clashes.
Encapsulation and Information Hiding
Encapsulation
- Encapsulation: bundling an object's data (fields) and the methods that work on it into one unit, the class.
- The data is hidden (
private); outside code can call only the methods the class offers. - Analogy: a medicine capsule. You never see the powder inside; you just swallow the capsule. Likewise, a class is the guardian of its own data: an invalid value (e.g. second 75) cannot get in.
Encapsulation is one of the four pillars of object-oriented programming (the others: inheritance, polymorphism, abstraction).
Encapsulation and Information Hiding
Information Hiding
- Information hiding is also called abstraction. A design should separate what is done from how it is done.
- A method should be usable without knowing its internals: knowing what it does should be enough.
- In a car we see and use the brake, the gas pedal and the steering wheel; we don't know their inner mechanics.
The same idea applies in code: we use System.out.println all the time without knowing how printing to the screen works.
Encapsulation and Information Hiding
Information Hiding: Code
public class DataService { private DbConnection conn; // usable without knowing the internals. public void addData(String data) { conn = new DbConnection(); conn.connect(); conn.addData(data); conn.close(); } }
public class Main { public static void main(String[] args) { DataService service = new DataService(); service.addData("Ayşe"); } }
Connection opened Added: Ayşe Connection closed
Mainonly saysservice.addData("Ayşe"): it states what it wants.- Opening the connection, writing the data and closing it (the how) are hidden inside
DataService. - The
connfield isprivate: no outside code can see or change it. DbConnectionis just a class that prints to the screen here; even with a real database driver,Mainwould not change.
Encapsulation and Information Hiding · Step-by-step code trace
Behind a Single Call: Step by Step
new DataService() creates an object on the heap; service points to it (a reference). conn is still null.
This call is all Main does. A new frame opens and the data parameter becomes "Ayşe".
The hidden work begins: a second object is created and the private conn field points to it.
connect() is called: three frames on the stack. Main knows nothing of it.
The data goes to the connection object's addData method: same name, different class.
The connection is closed. All three steps hide behind a single call.
main resumes. The user wrote one line and never saw the details: information hiding.
public class DataService { private DbConnection conn; // usable without knowing the internals. public void addData(String data) { conn = new DbConnection(); conn.connect(); conn.addData(data); conn.close(); } } public class Main { public static void main(String[] args) { DataService service = new DataService(); service.addData("Ayşe"); } }
Preconditions and Postconditions
Preconditions and Postconditions
Precondition
A condition assumed true before the method is called. Ensuring it is the caller's responsibility.
public class DataService { // Precondition: data != null public void addData(String data) { // check whether data is null // ... } }
Postcondition
If the precondition held, the state guaranteed to be true after the method finishes. Ensuring it is the method's responsibility.
public class DataService { // Postcondition: returns true if data was added public boolean addData(String data) { // check whether the data was added // ... return true; } }
true.” The user knows only the contract, not the body.Preconditions and Postconditions
Contract: A Complete Example
public class DataService { private int count = 0; /** * Adds a record to the database. * Precondition: data is not null or empty. * Postcondition: returns true if added, * and count grows by 1. */ public boolean addData(String data) { if (data == null || data.isEmpty()) { return false; // precondition broken } // ... add data to the database ... count++; return true; // postcondition met } public int getCount() { return count; } }
// in main: DataService service = new DataService(); System.out.println(service.addData("Ali")); System.out.println(service.addData("")); System.out.println(service.addData(null)); System.out.println(service.getCount());
true false false 1
/** ... */is a Javadoc comment: it explains how to use the method.- If the precondition is broken, the method adds nothing and returns
false.
Preconditions and Postconditions · Step-by-step code trace
Contract: Code Trace
The object was just created: count = 0. The contract: data must be neither null nor empty.
"Ayşe" is neither null nor empty: the condition is false; the if block is skipped.
The postcondition holds: the counter goes up by 1 and true is returned.
data == null is true; || short-circuits. null.isEmpty() is never called, so no NullPointerException is thrown.
Precondition broken: without touching the object, the method returns false.
"" is not null but empty: the right side is true, so again false. The counter is unchanged.
Valid data: the counter becomes 2, true.
Of the four calls, only the two that honor the contract added a record: 2. The object's state was never broken.
public boolean addData(String data) { if (data == null || data.isEmpty()) { return false; // precondition broken } count++; return true; // postcondition met } // in main: DataService service = new DataService(); System.out.println(service.addData("Ayşe")); System.out.println(service.addData(null)); System.out.println(service.addData("")); System.out.println(service.addData("Can")); System.out.println(service.getCount());
Preconditions and Postconditions
What If the Precondition Is Broken?
| Approach | Example | What does the caller notice? |
|---|---|---|
| Ignore silently | setSecond(75) does nothing | Nothing; the bug may go unnoticed |
| Return a status | addData(null) → false | Only if it checks the return value |
| Throw an exception | throw new IllegalArgumentException(...) | Uncaught, it stops the program; the error is not lost |
public void setSecond(int second) { if (second < 0 || second > 59) throw new IllegalArgumentException( "second must be 0-59: " + second); this.second = second; } // in main: DigitalClock s = new DigitalClock(); try { s.setSecond(30); s.setSecond(75); System.out.println("never reached"); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } System.out.println(s.getSecond());
Error: second must be 0-59: 75 30
- The exception exposes the bad value at the call site; the object's state does not change (it stays 30).
publicmethods: Java's usual choice for a bad argument isIllegalArgumentException.- Document the chosen approach as part of the contract.
Preconditions and Postconditions
Writing the Contract with Javadoc
/** * Withdraws money from the account. * @param amount sum to withdraw; {@code 0 < amount <= balance} * @return the balance after the call (old balance - amount) * @throws IllegalArgumentException if amount is out of range */ public double withdraw(double amount) { if (amount <= 0 || amount > balance) throw new IllegalArgumentException("Invalid amount: " + amount); balance -= amount; return balance; }
@param: each parameter and its precondition. @return: the return value, i.e. the postcondition. @throws: what happens when the contract is broken.
javadoc -d docs BankAccount.java generates HTML docs from these comments. The Java library's online docs are built the same way.
Write what the method does and how to use it. How it does it stays out: that is the hidden implementation, and it may change.
For the user, who never sees the body. A class's interface is its signatures plus these comments.
Preconditions and Postconditions
assert: Checking Invariants
class Counter { private int value; // invariant: 0 <= value <= 9 void increment() { value = value + 1; // bug: 10 after 9 assert value >= 0 && value <= 9 : "value=" + value; } } // in main: Counter s = new Counter(); for (int i = 0; i < 10; i++) s.increment(); System.out.println("done");
java Main
done
java -ea Main
Exception in thread "main" java.lang.AssertionError: value=10 at Counter.increment(Main.java:5)
assert condition : message;throws anAssertionErrorif the condition is false. It checks class invariants and postconditions during development.- Assertions are off by default;
-ea(enable assertions) turns them on. When they are off, the bug slips by silently:done. publicmethod arguments are not checked withassert: when assertions are off, nothing is checked. Exceptions for arguments; for internal consistency,assert.
Access Modifiers
Access Modifiers
- Access modifier: a keyword that sets who can access a class, field or method.
public: other classes can access it directly.private: accessible only from within the class; the compiler blocks outside access.- Classes are usually
public. - Fields are usually
private. - Fields are read and changed through
publicmethods.
public class Student { // public class private String name; // hidden field private int grade; // hidden field public int getGrade() { // public method return grade; } }
Rule: fields hidden, behavior public.
Access Modifiers
Four Access Levels
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✓ | ✗ |
| (none) package access | ✓ | ✓ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ |
- With no modifier, package access (package-private, “default”) applies: only classes in the same package have access.
protectedis for subclasses: a subclass in another package also has access.- As a rule, prefer the most restrictive level: start with
private, and open up only when truly needed. - A top-level class can only be
publicor package-private.
Access Modifiers
Trying to Access a private Field
public class Test { public static void main(String[] args) { DigitalClock s = new DigitalClock(); s.second = 75; } }
Test.java:4: error: second has private access in DigitalClock
s.second = 75;
^
1 errorsecondis declaredprivateinDigitalClock.- Writing
s.secondfrom another class is a compile error: the program never runs. - If the field were
public,s.second = 75;would be silently accepted and the clock would fall into an invalid state. - The fix: let the class's own method make the change:
s.setSecond(75);The method rejects the invalid value.
Access Modifiers
private Is Per Class
class Ratio { private int num, den; Ratio(int num, int den) { this.num = num; this.den = den; } Ratio times(Ratio other) { // other's private fields: allowed return new Ratio(num * other.num, den * other.den); } @Override public String toString() { return num + "/" + den; } } // in main: Ratio k = new Ratio(2, 3).times(new Ratio(3, 4)); System.out.println(k);
6/12
- Access control works per class, not per object:
Ratio's code can read everyRatioobject'sprivatefields. times,equals,compareTo: methods that work on two objects need no getters for this reason.- In another class, the same line does not compile:
error: num has private access in Ratio
Getters and Setters
The DigitalClock Class
public class DigitalClock { private int hour = 0; private int minute = 0; private int second = 0; public int getSecond() { return this.second; } public void setSecond(int second) { if (second >= 0 && second < 60) { this.second = second; } } }
- Getter (accessor): returns the field's value.
- Setter (mutator): checks the new value first, and assigns it if valid.
- In UML,
-means private,+means public.
Getters and Setters · Step-by-step code trace
Setter Protection: Step by Step
The object is created; its second field starts at 0. s points to the object.
setSecond(45): parameter second = 45. this is the object the method was called on. The condition is true.
In this.second = second; the left second is the object's field, the right one is the parameter. The field becomes 45.
setSecond(75): the condition is false, so the assignment is skipped. The invalid value cannot get in.
getSecond() returns the field's value: 45. The field is still valid.
It prints 45. The object's state stayed valid from start to finish: that is the point of encapsulation.
public class DigitalClock { private int second = 0; public int getSecond() { return this.second; } public void setSecond(int second) { if (second >= 0 && second < 60) { this.second = second; } } } // in ClockTest.main: DigitalClock s = new DigitalClock(); s.setSecond(45); s.setSecond(75); System.out.println(s.getSecond());
Getters and Setters
this and Shadowing
Correct
public void setSecond(int second) { if (second >= 0 && second < 60) { this.second = second; } }
Wrong (but compiles!)
public class Box { private int width; public int getWidth() { return width; } public void setWidth(int width) { width = width; } }
- If a parameter has the same name as a field, then inside the method
secondmeans the parameter: the parameter shadows the field. thisis the very object the method was called on.this.secondis always the field.- In the wrong version,
width = width;assigns the parameter to itself; the field never changes.k.setWidth(5), thenk.getWidth():
0
The compiler reports nothing; the bug shows up only at run time. That is why the this. habit matters in setters.
Getters and Setters
Accessor Methods
public class DigitalClock { private int hour = 0; // 0..23 private int minute = 0; // 0..59 private int second = 0; // 0..59 public int getHour() { return hour; } public int getMinute() { return minute; } public int getSecond() { return second; } public void setHour(int hour) { if (hour >= 0 && hour < 24) this.hour = hour; } public void setMinute(int minute) { if (minute >= 0 && minute < 60) this.minute = minute; } public void setSecond(int second) { if (second >= 0 && second < 60) this.second = second; } public void show() { System.out.printf("%02d:%02d:%02d%n", hour, minute, second); } }
DigitalClock s = new DigitalClock(); s.setHour(9); s.setMinute(5); s.setSecond(30); s.show(); s.setHour(24); // rejected s.setMinute(-3); // rejected s.show();
09:05:30 09:05:30
- Naming:
minute→getMinute(),setMinute(int). booleanfields use an accessor starting withis:isActive().
Getters and Setters
Why Not a public Field?
public field
public class Clock { public int second; } // in another class: s.second = -5; // accepted!
- Any code can write any value.
- The rule (0–59) is left to every user; one slip and the object is broken.
- If the field's name or type changes, every class that uses it must change.
private field + method
public class Clock { private int second; public void setSecond(int s) { if (s >= 0 && s < 60) second = s; } }
- The rule is checked in one place, inside the class.
- Read-only fields are possible: write only a getter.
- The internals may change while method signatures stay the same.
Java 16+: for immutable classes that only carry data, you can write record Point(int x, int y) { }; the fields automatically become private final, and the accessors are named x() and y().
Getters and Setters
Setter Protection: Interactive Demo
“set via setter” calls s.setSecond(75): an invalid value is rejected. “if field were public” writes directly, as in s.second = 75: the object falls into an invalid state (red). Valid ranges: hour 0–23, minute and second 0–59.
Example: Bank Account
BankAccount: Fields
public class BankAccount { private int accountNumber; // account number private double balance; // account balance private String accountType; // "Checking" / "Savings" public BankAccount(int accountNumber, double balance, String accountType) { this.accountNumber = accountNumber; this.balance = balance; this.accountType = accountType; } public int getAccountNumber() { return accountNumber; } public double getBalance() { return balance; } public String getAccountType() { return accountType; } // ... deposit and withdraw methods
- All three fields are
private: nobody can change the account number or balance directly. - The constructor sets up the object with its initial values, using the
this.balance = balanceidiom. - Getters only, no setters:
setBalancedoes not exist, so the balance changes only through transactions.
Example: Bank Account
BankAccount: Deposit and Withdraw
// ... // deposit public void deposit(double amount) { if (amount > 0) { balance += amount; System.out.println(amount + " TL deposited. New balance: " + balance); } else { System.out.println("Invalid deposit amount."); } } // withdraw public void withdraw(double amount) { if (amount <= balance && amount > 0) { balance -= amount; System.out.println(amount + " TL withdrawn. New balance: " + balance); } else if (amount > balance) { System.out.println("Insufficient balance."); } else { System.out.println("Invalid withdrawal amount."); } }
- Each operation first checks its precondition:
amount > 0, and for withdrawals alsoamount ≤ balance. - If the condition fails, the balance stays the same; only a message is printed.
- The balance can never go negative: this is the class's invariant.
Example: Bank Account
BankAccount: Interest
// ... // add interest (savings only) public void addInterest(double rate) { if (accountType.equals("Savings") && rate > 0) { double interest = balance * rate / 100; balance += interest; System.out.println("Adding interest: " + interest + " TL. New balance: " + balance); } else if (!accountType.equals("Savings")) { System.out.println( "Interest applies only to savings accounts."); } else { System.out.println("Invalid interest rate."); } }
- Interest is added only to savings accounts, at a positive rate.
- Strings are compared not with
==, but withequals. interestis a local variable: it exists only while the method runs and is not part of the object.
Example: Bank Account
BankAccount: Transfer
// ... // transfer to another account public void transfer(BankAccount target, double amount) { if (amount <= balance && amount > 0) { balance -= amount; target.deposit(amount); System.out.println(amount + " TL transferred. New balance: " + balance); } else { System.out.println( "Insufficient balance or invalid amount."); } } }
transfercalls a method on another object of the same class:target'sdeposit.- Writing directly to the target's
balancefield would also work (same class, andprivateis per class), but calling a method keeps the rules in one place.
Example: Bank Account · Step-by-step code trace
Two Accounts, One Transfer: Step by Step
The constructor runs: the first object is built on the heap with balance 2000.0.
A second, independent object. Each object has its own balance field.
this = acc1. amount > 0 is true: balance += amount → 2500.0.
This time this = acc2. 200 ≤ 1500: the balance becomes 1300.0; acc1 is unaffected.
A savings account: interest = 2500.0 × 5 / 100 = 125.0, balance 2625.0.
transfer: the condition is true, so it first deducts from its own balance: 2625.0 − 300.0 = 2325.0.
target.deposit(amount): 3 frames on the stack; now this = acc2, balance 1600.0.
deposit returns; transfer resumes where it left off and prints its own message.
The getters read the final balances. Total money is conserved: 2325 + 1600 = 3925 = 2625 + 1300.
// in main: BankAccount acc1 = new BankAccount(123456, 2000.0, "Savings"); BankAccount acc2 = new BankAccount(789012, 1500.0, "Checking"); acc1.deposit(500.0); acc2.withdraw(200.0); acc1.addInterest(5.0); acc1.transfer(acc2, 300.0); System.out.println(acc1.getBalance()); System.out.println(acc2.getBalance());
Example: Bank Account
The Constructor Must Validate Too
- Setters and transaction methods protect the balance, but the constructor in the example assigns its input without checking.
new BankAccount(1, -500.0, "Checking")creates an account with a negative balance; write"savings"(lowercase) and the account never earns interest, with no one noticing.- The class invariant must hold from the moment the object is born: the constructor is a precondition checker too.
- If the constructor throws, the
newexpression yields no reference: the invalid object never reaches the user.
public BankAccount(int accountNumber, double balance, String accountType) { if (balance < 0) throw new IllegalArgumentException( "Initial balance cannot be negative"); if (!accountType.equals("Savings") && !accountType.equals("Checking")) throw new IllegalArgumentException( "Unknown account type: " + accountType); this.accountNumber = accountNumber; this.balance = balance; this.accountType = accountType; }
The constructor is the only door into the object: if the rules are enforced there once, the class's other methods can trust that every object is valid.
Example: Bank Account · Step-by-step code trace
Validation in the Constructor: Code Trace
300 is valid: the condition is false; kelvin is assigned and a points to the new object.
b is explicitly set to null so it can still be read after the catch block.
new allocates the second object (kelvin defaults to 0.0) and calls the constructor. The parameter is −5.0.
Precondition broken: throw stops the constructor here. The assignment line never runs.
Control passes to the catch block. b = ... was cut short, so b did not change; no reference reaches the half-built object.
The program can only use valid Temperature objects: the invariant (kelvin ≥ 0) holds for every object.
class Temperature { private final double kelvin; public Temperature(double kelvin) { if (kelvin < 0) throw new IllegalArgumentException( "Kelvin cannot be negative"); this.kelvin = kelvin; } public double getKelvin() { return kelvin; } } // in main: Temperature a = new Temperature(300); Temperature b = null; try { b = new Temperature(-5); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } System.out.println(a.getKelvin() + " " + b);
Class Design
Class Design
- A class definition has two parts: interface and implementation.
- The interface states what the class does and how to use it: the names, parameters, return types and comments of the public methods.
- The implementation holds the class's internal mechanics and private fields, which matter only inside the class.
- The implementation may change while the interface stays the same; private fields are hidden from outside the class.
- Three parts: specification (constructor and method signatures), representation (the
privatefields that hold the data), and implementation (constructor and method bodies). Users know only the specification; their code survives changes to the representation and implementation.
Class Design
Interface
public interface Car { // Interface: WHAT is done? public void drive(); public void stop(); }
- In Java, an
interfaceis a contract that says what a class will do: the methods have only signatures, no bodies. - Whoever uses the car knows only the
drive()andstop()methods.
Class Design
Class Implementation
public class SportsCar implements Car { // Implementation: HOW is it done? private String brand; private int speed; public SportsCar(String brand) { this.brand = brand; } public void drive() { speed = 100; System.out.println(brand + " is moving: " + speed + " km/h"); } public void stop() { speed = 0; System.out.println(brand + " stopped."); } }
// in main: Car car = new SportsCar("Rüzgar"); car.drive(); car.stop();
Rüzgar is moving: 100 km/h Rüzgar stopped.
implements Car: the class must write every method of the interface.- An interface and a class in the same package cannot share a name (
duplicate class: Car); that is why the class is namedSportsCar. Maindeclares the variable as typeCar: it depends only on the interface.
Class Design
Changing the Implementation
Old: two separate fields
public class DigitalClock { private int minute = 0; private int second = 0; public int getMinute() { return minute; } public int getSecond() { return second; } public void setMinute(int minute) { if (minute >= 0 && minute < 60) { this.minute = minute; } } public void setSecond(int second) { if (second >= 0 && second < 60) { this.second = second; } } }
New: a single field
public class DigitalClock { // seconds since midnight private int totalSeconds = 0; public int getMinute() { return totalSeconds / 60 % 60; } public int getSecond() { return totalSeconds % 60; } public void setMinute(int minute) { if (minute >= 0 && minute < 60) { int diff = minute - getMinute(); totalSeconds += diff * 60; } } public void setSecond(int second) { if (second >= 0 && second < 60) { totalSeconds += second - getSecond(); } } }
setMinute(12); setSecond(45); setSecond(75);, both versions give 12:45.Class Design · Step-by-step code trace
Same Interface, New Implementation: Code Trace
The new version keeps one field; the old one (for comparison) keeps two. From outside, both read 00:00.
setMinute(12): a 12-minute difference, so 12 · 60 = 720 seconds are added. The old version simply writes minute = 12.
setSecond(45): the value is in range, the condition is true.
First, getSecond() = 720 % 60 = 0; the difference 45 is added: 765. From outside it reads 12:45.
75 is invalid: both versions reject it. The rule (0–59) stayed inside the class.
The difference can be negative: 9 − 45 = −36, total 729. The minute is still 12.
Output 12:9; the old version would give the same. The internal representation changed, yet not one character of main changed.
private int totalSeconds = 0; // one field public int getSecond() { return totalSeconds % 60; } public void setSecond(int second) { if (second >= 0 && second < 60) totalSeconds += second - getSecond(); } // getMinute(): totalSeconds / 60 % 60 DigitalClock s = new DigitalClock(); // main s.setMinute(12); s.setSecond(45); s.setSecond(75); s.setSecond(9); System.out.println(s.getMinute() + ":" + s.getSecond());
Class Design
Guidelines
- All variables (fields) in a class should be
private. - Provide only as many
publicaccessor methods as needed (you don't need an automatic setter for every field). - Add comments saying how to use each method: what it does and its pre- and postconditions.
- Internal-only helper methods should be
private.
public class Student { private int grade; private boolean isValid(int value) { return value >= 0 && value <= 100; } public void setGrade(int grade) { if (isValid(grade)) this.grade = grade; } }
If another class calls o.isValid(50):
error: isValid(int) has private access in Student
Class Design
Tell, Don't Ask
Writing a getter and a setter for every field is not encapsulation: if the rules are still enforced outside the class, the data has only moved one step away.
Asking: the rule lives in client code
// same check at every withdrawal if (h.getBalance() >= 300) { h.setBalance(h.getBalance() - 300); } // ...and wherever points are added o.setGrade(Math.min(100, o.getGrade() + 5));
- The rule repeats at every call site; one slip and the object is broken.
setBalance: once it exists, anyone can set the balance to anything.
Telling: the rule lives in the object
h.withdraw(300); // rule in BankAccount o.addBonus(5); // 100 cap in Student
- Instead of asking the object for its data and deciding for it, you tell it what you want; the object holding the data makes the decision.
- Write a setter only when the field can truly change freely.
BankAccounttherefore has nosetBalance.
Test question: “Who has the data needed to make this decision?” If the answer is the object itself, the decision belongs in its method.
Class Design
Benefits of Encapsulation
Simplifies the relation between an object and its user: the user knows only the methods.
Protects the object from unwanted, faulty access by users.
Without changing the interface, the class's internals can change; client code is unaffected.
The object's state always obeys the rules (class invariant):
- only points with positive coordinates,
- seconds and minutes between 0 and 59,
- hours never negative.
setSecond(75) is rejected, withdraw never takes the balance below zero, BankAccount's internals may change, yet code calling deposit stays the same.Class Design
Observations
- Interfaces change much less often than implementations: this keeps the code stable.
- When the implementation changes, code that depends on it directly must change too.
- Hiding the implementation reduces other classes' dependence on it: changes stay inside the class (loose coupling).
Immutable Classes
A Leaking Reference
public class ReportCard { private final int[] grades; public ReportCard(int[] grades) { this.grades = grades; // same array } public int[] getGrades() { return grades; // inner array } public double average() { int t = 0; for (int n : grades) t += n; return (double) t / grades.length; } }
int[] arr = {70, 80, 90}; ReportCard k = new ReportCard(arr); arr[0] = 0; // outside array k.getGrades()[1] = -100; // from the getter System.out.println(k.average());
-3.3333333333333335
- The field is
private final, with no setter; yet the grades changed from outside, and even an invalid grade like −100 got in. - The reason: an array is an object. The constructor and getter shared only the reference; the object is reachable from three places.
finalonly stops the reference from pointing to another array; it does not protect the array's contents.
Immutable Classes · Step-by-step code trace
A Leaking Reference: Code Trace
An array is an object on the heap; the arr variable holds only its reference.
The constructor writes the reference from its parameter into the field. Now ReportCard's private field and main's arr variable point to the same array.
arr[0] = 0 goes through none of ReportCard's methods, yet the grade ReportCard sees has changed.
getGrades() returns the inner array itself; −100 is written through the returned reference. An invalid grade got into the object without passing any check.
Average (0 − 100 + 90) / 3 ≈ −3.33. private alone was not enough: the reference to the inner object leaked out.
public ReportCard(int[] grades) { this.grades = grades; } public int[] getGrades() { return grades; } // in main: int[] arr = {70, 80, 90}; ReportCard k = new ReportCard(arr); arr[0] = 0; k.getGrades()[1] = -100; System.out.println(k.average());
Immutable Classes
Defensive Copying
public class ReportCard { private final int[] grades; public ReportCard(int[] grades) { this.grades = grades.clone(); // on entry } public int[] getGrades() { return grades.clone(); // on exit } // average() unchanged }
With the same main
80.0
- Defensive copy: a mutable object is copied when it enters and leaves the class. The only reference to the inner array stays the class's own field.
- The constructor's copy guards against the caller later changing its array; the getter's copy guards against changes to the returned array.
- For lists, use
new ArrayList<>(list)or the read-only viewCollections.unmodifiableList(list). String,Integerand other immutable objects are not copied: sharing them is harmless.
Copying has a cost; for large data, a read-only view or an immutable type from the start is cheaper.
Immutable Classes
Designing an Immutable Class
public final class Money { // no subclasses private final long cents; // assigned once private final String unit; public Money(long cents, String unit) { this.cents = cents; this.unit = unit; } public Money plus(Money other) { // instead of a setter if (!unit.equals(other.unit)) throw new IllegalArgumentException("Units differ"); return new Money(cents + other.cents, unit); } @Override public String toString() { return cents / 100 + "." + String.format("%02d", cents % 100) + " " + unit; } }
Rules
- No setters; the state is set only in the constructor.
- Fields are
private final. - The class is
final: no mutable subclass can be written. - “Modifying” methods return a new object.
- Mutable fields get defensive copies.
Payoff
- The invariant is checked only in the constructor; after that it can never break.
- The object can be shared without copying, can be a
HashMapkey, and is thread-safe. Stringandrecordare ready-made examples of these rules.
Immutable Classes · Step-by-step code trace
Immutable Money: Code Trace
The first object is built. Its fields are final: from now on no method can change them.
plus leaves a unchanged; it builds and returns a new object (#3) holding the sum.
The returned value was not assigned to a variable: #3 is lost. This is the most common mistake with immutable objects; a is unchanged.
This time the result is assigned to b: 1250 + 375 = 1625 cents. #4, built as the argument, is no longer used either.
a kept its initial value. String's toUpperCase() and concat() methods work the same way.
public Money plus(Money other) { if (!unit.equals(other.unit)) throw new IllegalArgumentException( "Units differ"); return new Money(cents + other.cents, unit); } // in main: Money a = new Money(1250, "TL"); a.plus(new Money(100, "TL")); // result lost Money b = a.plus(new Money(375, "TL")); System.out.println(a + " | " + b);
Packages
Packages
- Package: a group of classes collected in one folder. The folder's name is the package's name.
- Each
publicclass is defined in its own file, named after the class. - The file's first line declares its package:
package packagename; - The compiler and JVM look for packages starting from the class path roots; the package name gives the folder path from there. The default class path is the current directory (
.). - For nested folders, use a dot instead of
/or\:school/admin→school.admin. - Package names are lowercase; Java's own packages:
java.lang,java.util,java.io…
project/ ├── src/ │ ├── bank/ │ │ ├── Account.java // package bank; │ │ └── Helper.java // package bank; │ └── app/ │ └── Main.java // package app; └── out/ // compiler output ├── bank/ │ ├── Account.class │ └── Helper.class └── app/ └── Main.class
A class's full name includes its package: bank.Account, app.Main.
Packages
Package Example
package bank; public class Account { private double balance; public void deposit(double amount) { if (amount > 0) { balance += amount; } } public double getBalance() { return balance; } }
package app; import bank.Account; public class Main { public static void main(String[] args) { Account acc = new Account(); acc.deposit(250.0); System.out.println("Balance: " + acc.getBalance()); } }
> javac -d out src/bank/Account.java src/app/Main.java > java -cp out app.Main Balance: 250.0
-d out: .class files are written underout/with their package folders.-cp out: the class path; when running, give the class's full name.
Packages
Importing Classes
- To use a class from another package by its short name:
import packagename.ClassName;The whole package:import java.util.*;(not subpackages). - Without
import, you can also use the full name:java.util.Random. java.lang(String,Math,System) and classes in the same package are visible automatically.- Order: first
package, thenimports, then the class.import staticlets you use a static member without the class name.
import java.util.Scanner; import static java.lang.Math.sqrt; public class ImportDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); java.util.Random rnd = new java.util.Random(42); System.out.println(sqrt(n) + " " + Math.max(n, 10) + " " + rnd.nextInt(100)); } }
7.0 49 30
Scanner: short name via import.java.util.Random: full name, no import.sqrt:import static;Math.max:java.lang.
Packages
Package Access
package bank; class Helper { // not public static double vat(double amount) { return amount * 0.20; } }
package app; import bank.Helper; public class Main2 { }
Main2.java:3: error: Helper is not public in bank;
cannot be accessed from outside package
import bank.Helper;
^- Classes and members without a modifier have package access: they are visible only within their own package.
Helperis thebankpackage's internal business:Accountcan use it; theapppackage cannot.- A package is also a level of encapsulation: its classes are closed to the outside, and only the
publicones form the package's interface.
Packages
Package Naming and Subpackages
- To avoid name clashes, organizations start package names with their reversed domain name:
giresun.edu.tr→tr.edu.giresun.bank. - Dotted names map to folders:
tr/edu/giresun/bank/. - A subpackage is a separate package.
tr.edu.giresun.bank.reportcannot see the package-private members ofbank; similar names grant no access rights. import tr.edu.giresun.bank.*;does not import subpackages:import java.util.*;likewise skips the classes injava.util.function.
// tr/edu/giresun/bank/Helper.java package tr.edu.giresun.bank; class Helper { // package-private static double vat(double t) { return t * 0.20; } }
// tr/edu/giresun/bank/report/Report.java package tr.edu.giresun.bank.report; import tr.edu.giresun.bank.Helper; public class Report { double compute() { return Helper.vat(100); } }
error: Helper is not public in tr.edu.giresun.bank; cannot be accessed from outside package
If the package name and folder path don't match exactly, the compiler cannot find the class; that is why IDEs create folders from the package name.
Packages
Class Name Clashes
import java.util.*; import java.sql.*; public class Ambiguous { public static void main(String[] args) { Date date = null; } }
Ambiguous.java:6: error: reference to Date is ambiguous both class java.sql.Date in java.sql and class java.util.Date in java.util match
import java.util.Date; public class DateDemo { public static void main(String[] args) { Date start = new Date(0); // java.util java.sql.Date sqlDate = // full name java.sql.Date.valueOf("2024-09-16"); System.out.println(start.getTime()); System.out.println(sqlDate); } }
0 2024-09-16
- Classes in two different packages may share a name:
java.util.Dateandjava.sql.Date. - To resolve the ambiguity, use the package name: bring one in with
import, and write the other with its full name.
Summary
Summary
| Concept | Meaning | In Java |
|---|---|---|
| Encapsulation | Bundle data + methods into one unit, hide internal details | private fields, public methods |
| Information hiding | Separate “what” from “how” | Users know only the method signature |
| Pre-/postcondition | State assumed before / guaranteed after a call | Javadoc comment + if check |
| Access modifier | Who can access | public, protected, (package), private |
| Getter / setter | Method that reads / validates and changes a field | getSecond(), setSecond(int), this.second = second |
| Interface / implementation | The class's outside / inner mechanism | interface Car, class SportsCar implements Car |
| Package, import | Group of classes in a folder; short names from other packages | package bank;, import java.util.Scanner; |
| Class name clash | Same class name in different packages | Full name: java.sql.Date |
Summary
Common Mistakes (1)
error: second has private access in DigitalClocks.second = 75; is wrong; write s.setSecond(75); instead.
width = width; // compiles, field unchangedThe parameter shadows the field; getWidth() returns 0. Correct: this.width = width;
error: incompatible types: unexpected return valuepublic void getWidth() cannot return a value; the return type must be int.
public void setSecond(int s) { second = s; }This is no better than a public field; the setter must enforce the validity rule.
Summary
Common Mistakes (2)
error: cannot find symbol symbol: class ScannerAdd import java.util.Scanner; at the top of the file.
error: class Account is public, should be declared in a file named Account.javaThe file name must exactly match the public class's name.
error: Helper is not public in bank; cannot be accessed from outside packageEither make the class public, or use it only from the same package.
error: SportsCar is not abstract and does not override abstract method stop() in Carimplements: a class must write every method of its interface.
Summary
Common Mistakes (3)
return grades; exposes a mutable array or list. Return a copy or a read-only view.
private final int[] grades: the reference is fixed, not the array elements.
a.plus(p); or s.toUpperCase(); alone changes nothing: a = a.plus(p);
Even if setters check, new BankAccount(1, -500.0, ...) builds an invalid object. The constructor must enforce the rule too.
-ea off means the check never runs. public method arguments call for IllegalArgumentException.
import java.util.*; does not cover Function: cannot find symbol. java.util.function must be imported separately.
The rule drifts into client code. Design behavior first (withdraw, addBonus); you may not need a setter.
Ignoring an invalid value without a trace hides the bug; either document it in the contract or throw an exception.
Summary
Worked Problems (1)
DigitalClock t = new DigitalClock();
t.setHour(25);
t.setMinute(30);
t.setSecond(-1);
t.setSecond(59);
t.show();DigitalClock a = new DigitalClock(); DigitalClock b = a; a.setMinute(15); b.setMinute(45); b = new DigitalClock(); b.setMinute(10); System.out.println(a.getMinute() + " " + b.getMinute());
From the “Accessor Methods” slide: the DigitalClock class (hour 0–23, minute/second 0–59).
- What does the code on the left print?
- What does the code on the right print? How many
DigitalClockobjects are created?
Show answers
- 00:30:59. 25 and −1 are rejected by the setters; the hour keeps its initial value 0.
- 45 10.
b = acreates no new object; both variables point to the same object; 45 is its minute. Thenbis bound to a second object. Total: 2 objects.
Summary
Worked Problems (2)
public class Test { public static void main(String[] args) { DigitalClock s = new DigitalClock(); s.setSecond(30); // A int x = s.second; // B System.out.println(s.getSecond()); // C s.getSecond() = 10; // D s.setSecond("40"); // E } }
Which of lines A–E cause a compile error? Why?
Show answers
- B:
second has private access in DigitalClock. To read it, uses.getSecond(). - D:
unexpected type, required: variable, found: value. A method call is a value, not something you can assign to; writes.setSecond(10)instead. - E:
incompatible types: String cannot be converted to int. - A and C are fine: they call public methods.
Summary
Worked Problems (3)
BankAccount h = new BankAccount(111, 1000.0, "Checking"); h.withdraw(5000.0); h.deposit(-50.0); h.addInterest(3.0); h.withdraw(250.0); BankAccount v = new BankAccount(222, 100.0, "Savings"); h.transfer(v, 1000.0); h.transfer(v, 750.0); System.out.println(h.getBalance() + " " + v.getBalance());
BankAccount: what does this code print? Which balances appear on the last line?
Show answer
Insufficient balance. Invalid deposit amount. Interest applies only to savings accounts. 250.0 TL withdrawn. New balance: 750.0 Insufficient balance or invalid amount. 750.0 TL deposited. New balance: 850.0 750.0 TL transferred. New balance: 0.0 0.0 850.0
Summary
Worked Problems (4)
A) Non-copying ReportCard
int[] d = {50, 60}; ReportCard k = new ReportCard(d); int[] g = k.getGrades(); g[0] = 100; d[1] = 100; System.out.println(k.average());
B) Money class
Money p = new Money(100, "TL"); p.plus(p); p = p.plus(p); p.plus(new Money(1, "TL")); System.out.println(p);
- What does A print? And with the defensive-copying
ReportCard? - What does B print?
- A program calls
increment()ten times on aCounter. Run it without-eaand with-ea: what happens? Which run reveals the bug? Ratio: doesnew Ratio(1, 2).numcompile in another class?
Show answers
- 100.0:
d,gand the field all point to the same array; both writes reach the object. With copying, 55.0: both writes go to copies. - 2.00 TL: only the result of
p = p.plus(p)is kept (100 + 100); the other two results are discarded. -eaabsent: prints done, the bug stays hidden.-eaon: the tenth increment throwsAssertionError: value=10.- No:
num has private access in Ratio.privateaccess is allowed only inRatio's own code.
Summary
Exercises (1)
Student:privatenameandgrade; accept grades only in 0–100;isPassing()returnstrueif grade ≥ 50.Point: accept only non-negative coordinates;distance()returns the distance to the origin.Thermometer: store a Celsius value (reject anything below −273.15);getFahrenheit()computes the value without a separate field.
Answers / hints
if (grade >= 0 && grade <= 100) this.grade = grade;→setGrade(120)gives “0 false”,setGrade(75)gives “75 true”.- Have the constructor call the setters;
return Math.sqrt(x * x + y * y);→new Point(3, 4): 5.0;setX(-7)is rejected, x stays 3. return celsius * 9 / 5 + 32;→ 25 °C = 77.0 °F. A derived value is not stored in its own field;setCelsius(-300)leaves the value at 25.0.
Summary
Exercises (2)
Counter: give it onlyincrement(),reset(),getValue()methods. Why no setter?Student: move it into theschoolpackage, use it fromapp.Main, and write the compile and run commands.BankAccount: add a getter-onlytxCountfield that grows by 1 on each successful deposit or withdrawal. What are the two accounts' values at the end of the bank example (trace slide)?
Answers / hints
- The value should only grow by 1 or reset;
setValuewould break this rule. Threeincrement()→ 3,reset()→ 0. package school;andimport school.Student;→javac -d out src/school/Student.java src/app/Main.java,java -cp out app.Main.- acc1: 1 (only
deposit; interest and transfer don't call their ownwithdraw), acc2: 2 (withdraw+ transfer'sdeposit).
Summary
References
- Oracle, The Java Tutorials: "Controlling Access to Members of a Class", "Using the this Keyword", "Packages", "Interfaces".
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition (6.6 Access Control, 7 Packages and Modules, 7.5 Import Declarations, 15.12.2 method selection).
- P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapters 3 and 8: Classes and Objects).
- K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly, 2022 (Chapter 4: encapsulation).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022 (Chapter 4: Objects and Classes).
- J. Bloch, Effective Java, 3rd ed., Addison-Wesley, 2018 (Items 15–16: minimize accessibility; use accessor methods, not public fields).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 11: Designing Classes).