Chapter 4.2: Encapsulation

Object Oriented Programming with Java
Information hidingPre- and postconditionsAccess modifiersGetters and setters Interface and implementationImmutable classesPackages and imports
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Explain encapsulation

Show with examples how a class bundles data with the methods that use it, hides internal details (information hiding) and separates “what” from “how”.

Write method contracts

State a method's precondition and postcondition in a comment and check them in code.

Choose the right access

public, private, protected and package access: use a table to say who can reach each.

Write getters and setters

Make fields private and write validating accessors; use the this.field = field idiom.

Separate interface from implementation

Change a class's internals without changing its outside; meet interface and implements.

Use packages

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.
DigitalClock object (capsule)+ getSecond()+ setSecond(int)+ show()private datahour = 9minute = 5second = 30Other class(client)✓s.second = 75; → compile error

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.
Interface: what you seeWheelGas pedalBrake pedalImplementation: under the hoodSteering gearEngine, fuel injectionGearboxBrake hydraulics, ABS

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");
    }
}
Output
Connection opened
Added: Ayşe
Connection closed
  • Main only says service.addData("Ayşe"): it states what it wants.
  • Opening the connection, writing the data and closing it (the how) are hidden inside DataService.
  • The conn field is private: no outside code can see or change it.
  • DbConnection is just a class that prints to the screen here; even with a real database driver, Main would not change.

Encapsulation and Information Hiding · Step-by-step code trace

Behind a Single Call: Step by Step

StackHeapmain()serviceDataServiceconnnull

new DataService() creates an object on the heap; service points to it (a reference). conn is still null.

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnnull

This call is all Main does. A new frame opens and the data parameter becomes "Ayşe".

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnDbConnection(Main never sees this object)

The hidden work begins: a second object is created and the private conn field points to it.

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnDbConnection(Main never sees this object)

connect() is called: three frames on the stack. Main knows nothing of it.

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnDbConnection(Main never sees this object)

The data goes to the connection object's addData method: same name, different class.

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnDbConnection(Main never sees this object)

The connection is closed. All three steps hide behind a single call.

StackHeapmain()serviceDataServiceconnDbConnection(Main never sees this object)

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;
    }
}
Together they form the method's contract: “Give me non-empty data, and I will add it and return 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());
Output
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

StackHeapmain()serviceDataService #1count0

The object was just created: count = 0. The contract: data must be neither null nor empty.

StackHeapaddData()thisdata"Ayşe"main()serviceDataService #1count0data == nullfalse||data.isEmpty()false

"Ayşe" is neither null nor empty: the condition is false; the if block is skipped.

StackHeapaddData()thisdata"Ayşe"main()serviceDataService #1count1data == nullfalse||data.isEmpty()falseprecondition met → record added, true

The postcondition holds: the counter goes up by 1 and true is returned.

StackHeapaddData()thisdatanullmain()serviceDataService #1count1data == nulltrue||data.isEmpty()not evaluated

data == null is true; || short-circuits. null.isEmpty() is never called, so no NullPointerException is thrown.

StackHeapaddData()thisdatanullmain()serviceDataService #1count1data == nulltrue||data.isEmpty()not evaluatedprecondition broken → nothing added, false

Precondition broken: without touching the object, the method returns false.

StackHeapaddData()thisdata""main()serviceDataService #1count1data == nullfalse||data.isEmpty()trueprecondition broken → nothing added, false

"" is not null but empty: the right side is true, so again false. The counter is unchanged.

StackHeapaddData()thisdata"Can"main()serviceDataService #1count2data == nullfalse||data.isEmpty()falseprecondition met → record added, true

Valid data: the counter becomes 2, true.

StackHeapmain()serviceDataService #1count2

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?

ApproachExampleWhat does the caller notice?
Ignore silentlysetSecond(75) does nothingNothing; the bug may go unnoticed
Return a statusaddData(null) → falseOnly if it checks the return value
Throw an exceptionthrow 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).
  • public methods: Java's usual choice for a bad argument is IllegalArgumentException.
  • 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;
}
Tags

@param: each parameter and its precondition. @return: the return value, i.e. the postcondition. @throws: what happens when the contract is broken.

Generating docs

javadoc -d docs BankAccount.java generates HTML docs from these comments. The Java library's online docs are built the same way.

What goes in?

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 whom?

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 an AssertionError if 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.
  • public method arguments are not checked with assert: 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 public methods.
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.

Student- name : String (private)- grade : int (private)+ getGrade() : int (public)Other classo.getGrade() ✓o.grade ✗ error

Access Modifiers

Four Access Levels

ModifierSame classSame packageSubclass (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.
  • protected is 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 public or package-private.
public: everywhereprotected: + subclasses in other packagespackage access: same packageprivate: same class

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 error
  • second is declared private in DigitalClock.
  • Writing s.second from 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.
TestDigitalClock- second = 0+ setSecond(int) rejects if not 0..59s.second = 75; compile errors.setSecond(75); runs, value rejected

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 every Ratio object's private fields.
  • 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
Encapsulation's boundary is the class's source code. The inside is one author's responsibility; it is the outside users who are kept out.

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;
        }
    }
}
DigitalClock- hour: int = 0- minute: int = 0- second: int = 0+ getSecond(): int+ setSecond(int): void
  • 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

StackHeapmain()sDigitalClocksecond0

The object is created; its second field starts at 0. s points to the object.

StackHeapsetSecond(45)thissecond45main()sDigitalClocksecond045 ≥ 0 && 45 < 60 → true

setSecond(45): parameter second = 45. this is the object the method was called on. The condition is true.

StackHeapsetSecond(45)thissecond45main()sDigitalClocksecond45

In this.second = second; the left second is the object's field, the right one is the parameter. The field becomes 45.

StackHeapsetSecond(75)thissecond75main()sDigitalClocksecond4575 < 60 → false

setSecond(75): the condition is false, so the assignment is skipped. The invalid value cannot get in.

StackHeapgetSecond()thismain()sDigitalClocksecond45

getSecond() returns the field's value: 45. The field is still valid.

StackHeapmain()sDigitalClocksecond45

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 second means the parameter: the parameter shadows the field.
  • this is the very object the method was called on. this.second is always the field.
  • In the wrong version, width = width; assigns the parameter to itself; the field never changes. k.setWidth(5), then k.getWidth():
Output
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();
Output
09:05:30
09:05:30
  • Naming: minute → getMinute(), setMinute(int).
  • boolean fields use an accessor starting with is: 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

 
hour9
minute5
second30
09:05:30
Pick a field and a value to compare the two paths.

“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 = balance idiom.
  • Getters only, no setters: setBalance does 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 also amount ≤ 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 with equals.
  • interest is 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.");
    }
  }
}
  • transfer calls a method on another object of the same class: target's deposit.
  • Writing directly to the target's balance field would also work (same class, and private is per class), but calling a method keeps the rules in one place.
acc1 objectbalance2000.0 → 1700.0acc2 objectbalance1500.0 → 1800.0target.deposit(300.0)transfer(acc2, 300.0): balance -= 300deposit's own rule: balance += 300

Example: Bank Account · Step-by-step code trace

Two Accounts, One Transfer: Step by Step

StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2000.0accountType"Savings"?

The constructor runs: the first object is built on the heap with balance 2000.0.

StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2000.0accountType"Savings"BankAccountaccountNumber789012balance1500.0accountType"Checking"

A second, independent object. Each object has its own balance field.

StackHeapmain()acc1acc2BankAccountthisaccountNumber123456balance2500.0accountType"Savings"BankAccountaccountNumber789012balance1500.0accountType"Checking"

this = acc1. amount > 0 is true: balance += amount → 2500.0.

StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2500.0accountType"Savings"BankAccountthisaccountNumber789012balance1300.0accountType"Checking"

This time this = acc2. 200 ≤ 1500: the balance becomes 1300.0; acc1 is unaffected.

StackHeapmain()acc1acc2BankAccountthisaccountNumber123456balance2625.0accountType"Savings"BankAccountaccountNumber789012balance1300.0accountType"Checking"

A savings account: interest = 2500.0 × 5 / 100 = 125.0, balance 2625.0.

StackHeapmain()acc1acc2BankAccountthisaccountNumber123456balance2325.0accountType"Savings"BankAccounttargetaccountNumber789012balance1300.0accountType"Checking"

transfer: the condition is true, so it first deducts from its own balance: 2625.0 − 300.0 = 2325.0.

StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2325.0accountType"Savings"BankAccountthisaccountNumber789012balance1600.0accountType"Checking"

target.deposit(amount): 3 frames on the stack; now this = acc2, balance 1600.0.

StackHeapmain()acc1acc2BankAccountthisaccountNumber123456balance2325.0accountType"Savings"BankAccounttargetaccountNumber789012balance1600.0accountType"Checking"

deposit returns; transfer resumes where it left off and prints its own message.

StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2325.0accountType"Savings"BankAccountaccountNumber789012balance1600.0accountType"Checking"

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 new expression 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

StackHeapmain()ab?Temperature #1kelvin300.0300 ≥ 0: object built

300 is valid: the condition is false; kelvin is assigned and a points to the new object.

StackHeapmain()abnullTemperature #1kelvin300.0b points to no object yet

b is explicitly set to null so it can still be read after the catch block.

StackHeapTemperature(kelvin)kelvin-5.0main()abnullTemperature #1kelvin300.0Temperature #2kelvin0.0half-builtnew allocated; constructor runs

new allocates the second object (kelvin defaults to 0.0) and calls the constructor. The parameter is −5.0.

StackHeapTemperature(kelvin)kelvin-5.0main()abnullTemperature #1kelvin300.0Temperature #2kelvin0.0no reference to itthrow: constructor cut short

Precondition broken: throw stops the constructor here. The assignment line never runs.

StackHeapmain()abnullTemperature #1kelvin300.0Temperature #2kelvin0.0left for the GCno assignment: b is still null

Control passes to the catch block. b = ... was cut short, so b did not change; no reference reaches the half-built object.

StackHeapmain()abnullTemperature #1kelvin300.0invalid Temperature never born

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 private fields that hold the data), and implementation (constructor and method bodies). Users know only the specification; their code survives changes to the representation and implementation.
UserControl panel(interface)StartWater amountStopInside (implementation)PumpBoiler, heaterFlow valveSolenoid valveBrew group

Class Design

Interface

public interface Car {
    // Interface: WHAT is done?
    public void drive();

    public void stop();
}
  • In Java, an interface is a contract that says what a class will do: the methods have only signatures, no bodies.
  • Whoever uses the car knows only the drive() and stop() methods.
«interface»Car+ drive(): void+ stop(): voidimplementsSportsCar- brand: String- speed: int+ SportsCar(brand: String)+ drive(): void+ stop(): void

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();
Output
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 named SportsCar.
  • Main declares the variable as type Car: 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();
    }
  }
}
Client code is unchanged: after setMinute(12); setSecond(45); setSecond(75);, both versions give 12:45.

Class Design · Step-by-step code trace

Same Interface, New Implementation: Code Trace

StackHeapmain()sNew versiontotalSeconds0getMinute()0getSecond()0Old versionminute0second0

The new version keeps one field; the old one (for comparison) keeps two. From outside, both read 00:00.

StackHeapmain()sNew versiontotalSeconds720getMinute()12getSecond()0Old versionminute12second012 · 60 = 720

setMinute(12): a 12-minute difference, so 12 · 60 = 720 seconds are added. The old version simply writes minute = 12.

StackHeapmain()sNew versiontotalSeconds720getMinute()12getSecond()0Old versionminute12second045 valid (0–59)

setSecond(45): the value is in range, the condition is true.

StackHeapmain()sNew versiontotalSeconds765getMinute()12getSecond()45Old versionminute12second45720 + (45 − 720 % 60) = 720 + 45 = 765

First, getSecond() = 720 % 60 = 0; the difference 45 is added: 765. From outside it reads 12:45.

StackHeapmain()sNew versiontotalSeconds765getMinute()12getSecond()45Old versionminute12second4575 < 60 false → no change

75 is invalid: both versions reject it. The rule (0–59) stayed inside the class.

StackHeapmain()sNew versiontotalSeconds729getMinute()12getSecond()9Old versionminute12second9765 + (9 − 45) = 729

The difference can be negative: 9 − 45 = −36, total 729. The minute is still 12.

StackHeapmain()sNew versiontotalSeconds729getMinute()12getSecond()9Old versionminute12second9729 / 60 % 60 = 12 · 729 % 60 = 9

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

  1. All variables (fields) in a class should be private.
  2. Provide only as many public accessor methods as needed (you don't need an automatic setter for every field).
  3. Add comments saying how to use each method: what it does and its pre- and postconditions.
  4. 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. BankAccount therefore has no setBalance.

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

Abstraction

Simplifies the relation between an object and its user: the user knows only the methods.

Protection

Protects the object from unwanted, faulty access by users.

Modifiability

Without changing the interface, the class's internals can change; client code is unaffected.

Valid state (invariant)

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.
In this chapter's examples: 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

BankReportTestInterfacepublic methodsdeposit()withdraw()getBalance()stableImplementationprivate fieldsbalancehelper methodscan change
  • 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.
  • final only 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

StackHeapmain()arrk?int[3][0]70[1]80[2]90array object; arr points to it

An array is an object on the heap; the arr variable holds only its reference.

StackHeapReportCard(grades)gradesmain()arrk?int[3][0]70[1]80[2]90ReportCardgradesconstructor copied the 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.

StackHeapmain()arrkint[3][0]0[1]80[2]90ReportCardgradeswritten outside: ReportCard unaware

arr[0] = 0 goes through none of ReportCard's methods, yet the grade ReportCard sees has changed.

StackHeapmain()arrkint[3][0]0[1]-100[2]90ReportCardgradesgetter leaked the inner reference

getGrades() returns the inner array itself; −100 is written through the returned reference. An invalid grade got into the object without passing any check.

StackHeapmain()arrkint[3][0]0[1]-100[2]90ReportCardgrades(0 − 100 + 90) / 3

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 view Collections.unmodifiableList(list).
  • String, Integer and 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

  1. No setters; the state is set only in the constructor.
  2. Fields are private final.
  3. The class is final: no mutable subclass can be written.
  4. “Modifying” methods return a new object.
  5. 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 HashMap key, and is thread-safe.
  • String and record are ready-made examples of these rules.

Immutable Classes · Step-by-step code trace

Immutable Money: Code Trace

StackHeapmain()ab?Money #1cents1250unit"TL"a: 12.50 TL

The first object is built. Its fields are final: from now on no method can change them.

StackHeapa.plus(other)othermain()ab?Money #1cents1250unit"TL"Money #2cents100Money #3cents1350plus builds a new object

plus leaves a unchanged; it builds and returns a new object (#3) holding the sum.

StackHeapmain()ab?Money #1cents1250unit"TL"Money #2cents100Money #3cents1350result unassigned: losta still 12.50 TL

The returned value was not assigned to a variable: #3 is lost. This is the most common mistake with immutable objects; a is unchanged.

StackHeapmain()abMoney #1cents1250unit"TL"Money #5cents1625unit"TL"b = 1250 + 375 = 1625 cents

This time the result is assigned to b: 1250 + 375 = 1625 cents. #4, built as the argument, is no longer used either.

StackHeapmain()abMoney #1cents1250unit"TL"Money #5cents1625unit"TL"two unchanging objects

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 public class 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());
    }
}
Command line (inside project/)
> 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 under out/ 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, then imports, then the class. import static lets 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));
  }
}
Output (input: 49)
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.
  • Helper is the bank package's internal business: Account can use it; the app package cannot.
  • A package is also a level of encapsulation: its classes are closed to the outside, and only the public ones 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.report cannot see the package-private members of bank; similar names grant no access rights.
  • import tr.edu.giresun.bank.*; does not import subpackages: import java.util.*; likewise skips the classes in java.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);
  }
}
Output
0
2024-09-16
  • Classes in two different packages may share a name: java.util.Date and java.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

ConceptMeaningIn Java
EncapsulationBundle data + methods into one unit, hide internal detailsprivate fields, public methods
Information hidingSeparate “what” from “how”Users know only the method signature
Pre-/postconditionState assumed before / guaranteed after a callJavadoc comment + if check
Access modifierWho can accesspublic, protected, (package), private
Getter / setterMethod that reads / validates and changes a fieldgetSecond(), setSecond(int), this.second = second
Interface / implementationThe class's outside / inner mechanisminterface Car, class SportsCar implements Car
Package, importGroup of classes in a folder; short names from other packagespackage bank;, import java.util.Scanner;
Class name clashSame class name in different packagesFull name: java.sql.Date

Summary

Common Mistakes (1)

Accessing a private field from outsideerror: second has private access in DigitalClock

s.second = 75; is wrong; write s.setSecond(75); instead.

Forgetting this in a setterwidth = width; // compiles, field unchanged

The parameter shadows the field; getWidth() returns 0. Correct: this.width = width;

Declaring a getter voiderror: incompatible types: unexpected return value

public void getWidth() cannot return a value; the return type must be int.

Setter without validationpublic 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)

Forgetting importerror: cannot find symbol symbol: class Scanner

Add import java.util.Scanner; at the top of the file.

public class ≠ file nameerror: class Account is public, should be declared in a file named Account.java

The file name must exactly match the public class's name.

Using a package-private class from outsideerror: Helper is not public in bank; cannot be accessed from outside package

Either make the class public, or use it only from the same package.

Not implementing an interface methoderror: SportsCar is not abstract and does not override abstract method stop() in Car

implements: a class must write every method of its interface.

Summary

Common Mistakes (3)

Exposing an inner object via a getter

return grades; exposes a mutable array or list. Return a copy or a read-only view.

Thinking a final field is immutable

private final int[] grades: the reference is fixed, not the array elements.

Forgetting to assign the new object

a.plus(p); or s.toUpperCase(); alone changes nothing: a = a.plus(p);

Not validating in the constructor

Even if setters check, new BankAccount(1, -500.0, ...) builds an invalid object. The constructor must enforce the rule too.

Checking arguments with assert

-ea off means the check never runs. public method arguments call for IllegalArgumentException.

Assuming subpackages are imported

import java.util.*; does not cover Function: cannot find symbol. java.util.function must be imported separately.

A setter for every field

The rule drifts into client code. Design behavior first (withdraw, addBonus); you may not need a setter.

Silently swallowing errors

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).

  1. What does the code on the left print?
  2. What does the code on the right print? How many DigitalClock objects are created?
Show answers
  1. 00:30:59. 25 and −1 are rejected by the setters; the hour keeps its initial value 0.
  2. 45 10. b = a creates no new object; both variables point to the same object; 45 is its minute. Then b is 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, use s.getSecond().
  • D: unexpected type, required: variable, found: value. A method call is a value, not something you can assign to; write s.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);
  1. What does A print? And with the defensive-copying ReportCard?
  2. What does B print?
  3. A program calls increment() ten times on a Counter. Run it without -ea and with -ea: what happens? Which run reveals the bug?
  4. Ratio: does new Ratio(1, 2).num compile in another class?
Show answers
  1. 100.0: d, g and the field all point to the same array; both writes reach the object. With copying, 55.0: both writes go to copies.
  2. 2.00 TL: only the result of p = p.plus(p) is kept (100 + 100); the other two results are discarded.
  3. -ea absent: prints done, the bug stays hidden. -ea on: the tenth increment throws AssertionError: value=10.
  4. No: num has private access in Ratio. private access is allowed only in Ratio's own code.

Summary

Exercises (1)

  1. Student: private name and grade; accept grades only in 0–100; isPassing() returns true if grade ≥ 50.
  2. Point: accept only non-negative coordinates; distance() returns the distance to the origin.
  3. Thermometer: store a Celsius value (reject anything below −273.15); getFahrenheit() computes the value without a separate field.
Answers / hints
  1. if (grade >= 0 && grade <= 100) this.grade = grade; → setGrade(120) gives “0 false”, setGrade(75) gives “75 true”.
  2. 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.
  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)

  1. Counter: give it only increment(), reset(), getValue() methods. Why no setter?
  2. Student: move it into the school package, use it from app.Main, and write the compile and run commands.
  3. BankAccount: add a getter-only txCount field 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
  1. The value should only grow by 1 or reset; setValue would break this rule. Three increment() → 3, reset() → 0.
  2. package school; and import school.Student; → javac -d out src/school/Student.java src/app/Main.java, java -cp out app.Main.
  3. acc1: 1 (only deposit; interest and transfer don't call their own withdraw), acc2: 2 (withdraw + transfer's deposit).

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).

The End

Chapter 4.2: Encapsulation
Previous: Chapter 4.1: Objects and Classes · Next: Chapter 4.3: Inheritance
1 / 1 Sercan KÜLCÜ. All rights reserved.