Object-Oriented Programming with Java · Lecture Notes

Chapter 4.2: Encapsulation

Writing a class begins with bringing data and the methods that work on it together. But this togetherness is not enough by itself. If the fields are open to everyone, every user changes the object as they please; a clock with 75 seconds or an account with a negative balance appears. Encapsulation closes the object's data off from the outside and allows it to be reached only through the class's own methods. The rules are then enforced in a single place, inside the class. These notes build this idea step by step. The first sections explain information hiding, the "what / how" distinction and the contract made of a method's preconditions and postconditions. Access modifiers, getter and setter methods and a detailed trace of a bank account class follow. The notes then separate the interface from the implementation and examine leaked references and immutable classes. The last section covers grouping classes in packages and the import declaration. All programs were compiled and run with JDK 21; the outputs, the final values in the trace tables and the compiler messages come from those runs.

Learning outcomes

Explain encapsulation
Explain with examples gathering data and the methods that process it in one class, hiding internal details (information hiding) and the "what / how" distinction.
Write a method contract
State a method's precondition and postcondition in a Javadoc comment; choose what to do when the precondition is broken and implement it in code.
Choose access correctly
Say who can reach members at the public, protected, package and private levels; read the access errors the compiler gives.
Write getters and setters
Make fields private and write access methods that validate; know the this.field = field pattern and the shadowing trap.
Separate interface from implementation
Change a class's internal structure without changing its outside face; meet interface and implements; close a leaked reference with a defensive copy and design an immutable class.
Use packages
Group classes with package and import, compile and run a packaged program on the command line, and resolve class name clashes.

4.2.1Encapsulation and information hiding

Once the fields and methods of a class have been defined, the first design question is this: who may touch these fields? If every field of a class can be read and written from anywhere, the class's own rules stay on paper. The seconds of a clock must be between 0 and 59. The class knows the rule, but every line that changes the field has to remember it separately. If the program has hundreds of lines, forgetting it in one of them is inevitable. Encapsulation solves this problem at the root: it leaves the job of enforcing the rule to the class itself.

4.2.1.1What is encapsulation?

Definition 4.2.1

Encapsulation is gathering an object's data (its fields) and the methods that process this data in a single unit, the class. The data is closed off from the outside (private); from outside, only the methods the class offers can be called.

There are two separate ideas in the definition. The first is bringing together: the data and the code that processes it stay in the same class. The second is closing off: the data is not directly visible or changeable from outside. Without the second idea the first is half-done. A class with public fields also keeps data and methods together, but it does not protect the data.

Encapsulation can be compared to a medicine capsule. The powder inside the capsule is not visible; the patient only swallows the capsule and does not care how the powder was prepared. A class is likewise the guardian of its own data. A call that wants to make the seconds 75 cannot pass through the door of the class. Figure 4.2.1 shows this arrangement on a DigitalClock object.

DigitalClock object (capsule)+ getSecond()+ setSecond(int)+ show()private datahour = 9minute = 5second = 30Other class(client)✓s.second = 75; → compile error
Figure 4.2.1: An encapsulated DigitalClock object. The private data (hour, minute, second) is inside the object and closed to the outside. Another class can call only the open methods such as getSecond(), setSecond(int) and show(). An attempt to write to the field directly (s.second = 75;) is stopped by a compile error.

The dashed red arrow in the figure shows the most concrete gain of encapsulation. Writing to the field directly is not a run-time error but a compile error. The program can never see the wrong value, because such a program does not compile. Stopping the invalid value is not left to run time; the compiler catches it while the code is being written.

Encapsulation is one of the four basic principles of object-oriented programming. The others are inheritance, polymorphism and abstraction. The four complement each other: inheritance and polymorphism organize the relations between classes; encapsulation and abstraction determine how a single class appears to the outside.

4.2.1.2Information hiding: what and how

Definition 4.2.2

Information hiding is the principle of hiding the internal structure of a class from those who use it. The design separates what a task does from how it is done. The user knows only what the method is for; the method can be used correctly without knowing the internal details.

Information hiding is a concept intertwined with abstraction, and some sources refer to the two by the same name. Abstraction means setting detail aside and showing only the important features. Information hiding makes sure that these details really do not reach the user. One is a point of view, the other is the wall that protects that point of view.

The best-known everyday example is the car. The driver sees and uses the steering wheel, the accelerator pedal and the brake. The driver does not need to know how the steering box, the fuel injection or the brake hydraulics work. Even if the manufacturer changes the engine, the driver goes on driving the car in the same way. Figure 4.2.2 draws this distinction as two layers.

Interface: what you seeWheelGas pedalBrake pedalImplementation: under the hoodSteering gearEngine, fuel injectionGearboxBrake hydraulics, ABS
Figure 4.2.2: The car analogy. On the left the interface the driver sees (steering wheel, accelerator pedal, brake pedal), on the right the hidden implementation under the hood (steering box, engine and fuel injection, transmission, brake hydraulics and ABS). Each control activates one or several internal parts the driver knows nothing about.

The same idea is used in Java every day. The System.out.println method is called constantly, but there is no need to know how the characters are sent to the screen. Details such as the code that talks to the operating system, character encoding and buffer memory are hidden behind println. The only thing the user knows is what the method does: it prints the given value and moves to the end of the line.

4.2.1.3Behind a single call

To see information hiding in code, consider a small class that adds a record to a database. The DataService class gathers the steps of opening the connection, writing the data and closing the connection inside a single method:

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");
    }
}

To compile this program a DbConnection class is also needed. In a real application this class would talk to a database driver. In the example of these notes it is a simple class that only prints to the screen:

public class DbConnection {
    public void connect() { System.out.println("Connection opened"); }
    public void addData(String data) { System.out.println("Added: " + data); }
    public void close() { System.out.println("Connection closed"); }
}
Connection opened
Added: Ayşe
Connection closed

The only thing the Main class does is the call service.addData("Ayşe"). This line says what is wanted: "add the record Ayşe." Opening the connection, writing the data and closing the connection, that is, how the job is done, is hidden inside DataService. Because the conn field is private, Main can neither see nor change it. If tomorrow a real driver were used instead of DbConnection, not a single line of Main would change.

What happens behind the call is given step by step in Table 4.2.1. The line numbers follow the layout of the trace code in which the two classes are written one after the other: lines 1–10 are the DataService class and lines 11–16 the Main class.

Table 4.2.1: Trace of the call service.addData("Ayşe"). In the call stack column the rightmost frame is the topmost; the variables column shows the frame running at that moment.
StepLineCall stackVariablesNew output
113: DataService service = new DataService();main()service=→DataService—
24: public void addData(String data) {main() → service.addData("Ayşe")data="Ayşe"—
35: conn = new DbConnection();main() → service.addData("Ayşe")data="Ayşe", conn=→object—
46: conn.connect();main() → service.addData("Ayşe") → conn.connect()data="Ayşe"Connection opened
57: conn.addData(data);main() → service.addData("Ayşe") → conn.addData(data)data="Ayşe"Added: Ayşe
68: conn.close();main() → service.addData("Ayşe") → conn.close()data="Ayşe"Connection closed
715: }main()service=→DataService—

In the first step new DataService() creates an object on the heap. The service variable is a reference to this object. The object's conn field is still null, because the default value of fields of reference type is null. In the second step addData is called; a new frame is added to the stack and the data parameter receives the value "Ayşe".

In the third step the hidden work begins. A second object is created and the private conn field points to it. Figure 4.2.3 gives this moment and the end of the call side by side. In the fourth step connect() is called; there are now three frames on the stack: main, addData and connect. Main is aware of none of these frames. In the fifth step the data goes to the addData method of the connection object. The two methods have the same name but belong to different classes; Java knows which one is called from the type of the object. In the sixth step the connection is closed.

StackHeapmain()serviceaddDatadata"Ayşe"DataServiceconnDbConnection(Main never sees this object) StackHeapmain()serviceDataServiceconnDbConnection(Main never sees this object)
Figure 4.2.3: Two moments of a single call. Left: addData is running; the private conn field of the DataService object points to the newly created DbConnection object. Right: the call has ended and only main is left on the stack; the connection object sits in a place the user never sees.

In the seventh step the flow returns to main. The user wrote one line and knew none of the three separate operations. This is exactly what information hiding means. This arrangement has no cost: every frame added to the call stack is opened and closed in constant time. The hidden work is the same work that would have to be done if it were not hidden.

Common mistake

Writing code that uses the hidden detail outside. A programmer who opens and closes the connection in Main does the work of DataService a second time. When the form of the connection changes, two places have to be fixed. Where a class offers a task with a single call, the steps of that task are not rewritten outside.

4.2.2Preconditions and postconditions

Information hiding asks that the user need not know the inside of the method. But the user must know one thing: in what situation does the method work correctly, and what does it guarantee when it does? This information is not inside the code but on the outer face of the method. This section describes the agreement a method makes with its user and how this agreement is enforced in code.

4.2.2.1The contract of a method

Definition 4.2.3

A precondition is a condition assumed to be true before the method is called; ensuring it is the caller's responsibility. A postcondition is the state guaranteed to be true after the method finishes, provided the precondition was met; ensuring it is the method's responsibility. Together they make up the method's contract.

The contract has two sides. The caller says "I am giving non-empty data", and the method answers "And I add it and return true." The user knows only the contract, not the body. If the precondition is broken, the method does not have to guarantee anything. This means responsibility is shared openly: if the fault is in the value the caller gave, the caller fixes it; if the method gives a wrong result with a correct value, the method is fixed.

A precondition and a postcondition can be written as comment lines as a first step. The two small pieces in the slides state first the precondition and then the postcondition of the same addData method:

public class DataService {
    // Precondition: data != null
    public void addData(String data) {
        // check whether data is null
        // ...
    }
}
public class DataService {
    // Postcondition: returns true if data was added
    public boolean addData(String data) {
        // check whether the data was added
        // ...
        return true;
    }
}

In the second piece the return type of the method has also changed: boolean instead of void. Because the postcondition says "returns true if added", the method has to return a value. Writing the contract forces one to think about the method's signature as well.

4.2.2.2Enforcing the contract in code

A comment line checks nothing by itself. The version below both writes the contract in the comment and enforces it on the first line of the body:

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;
  }
}

The /** ... */ at the top of the method is a Javadoc comment: it explains how the method is to be used and can be turned into documentation with tools. The first job of the body is to check the precondition. If data is null or empty, the method returns false without touching the object. If the precondition holds, the record is added, count goes up by one and true is returned; the postcondition is thus fulfilled. The first main method in the slides makes three calls:

// 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

The trace of four calls is given in Table 4.2.2. This time "Ayşe", null, "" and "Can" are tried in turn. The line numbers follow the layout of the trace code: lines 1–7 are addData and lines 9–14 are in main.

Table 4.2.2: Trace of the addData contract with four calls. count in the variables column is the object's field.
StepLineVariablesNew output
19: DataService service = new DataService();service=→#1, count=0—
210: System.out.println(service.addData("Ayşe"));
2: if (data == null || data.isEmpty()) {
data="Ayşe", count=0—
35: count++;
6: return true; // postcondition met
data="Ayşe", count=1true
411: System.out.println(service.addData(null));
2: if (data == null || data.isEmpty()) {
data=null, count=1—
53: return false; // precondition brokendata=null, count=1false
612: System.out.println(service.addData(""));
2: if (data == null || data.isEmpty()) {
3: return false; // precondition broken
data="", count=1false
713: System.out.println(service.addData("Can"));
5: count++;
6: return true; // postcondition met
data="Can", count=2true
814: System.out.println(service.getCount());count=22

In the second step "Ayşe" is neither null nor empty. Both sides of the || operator are false, and the if block is skipped. In the third step the counter becomes 1 and true is returned. The fourth step is the most instructive: data == null is true and || short-circuits. Because the left side is true, the right side is never evaluated; the call null.isEmpty() is not made and no NullPointerException occurs. Figure 4.2.4 shows this case side by side with the empty-string case.

StackHeapaddData()thisdatanullmain()serviceDataService #1count1data == nulltrue||data.isEmpty()not evaluated StackHeapaddData()thisdata""main()serviceDataService #1count1data == nullfalse||data.isEmpty()trueprecondition broken → nothing added, false
Figure 4.2.4: The precondition broken in two different ways. Left: data is null; data == null is true and data.isEmpty() is never evaluated. Right: data is the empty string; the first condition is false and the second is true. In both cases count stays at 1.

This is why the order of the conditions matters. Had it been written as data.isEmpty() || data == null, isEmpty() would be called first on a null argument and the program would stop with a NullPointerException. When tried with JDK 21 this is indeed what happens. First the null check, then the call on the object: this order is always kept in Java.

In the sixth step the empty string arrives. "" is an object, not null; but because its length is 0, isEmpty() returns true. In the seventh step "Can" is added and the counter becomes 2. Of the four calls, only the two that kept the contract added a record. The state of the object was never corrupted in any call.

One more detail: " " (a single space) passes the isEmpty() test, because its length is 1. When addData(" ") is sent to the same object, the method returns true and counts the record. If data made up of spaces should also be rejected, the condition is written with data.trim().isEmpty() or, since Java 11, data.isBlank(). What exactly the precondition says determines what is checked in the code.

The cost of checking the precondition is small: two comparisons and at most one method call, that is, constant time. Its gain, on the other hand, is large; an invalid record can never get into the object.

4.2.2.3When the precondition is broken

What the method does when the precondition is broken is also a design decision. Table 4.2.3 compares three common approaches.

Table 4.2.3: Three approaches to choose from when the precondition is broken.
ApproachExampleWhat does the caller notice?
Silently ignoresetSecond(75) does nothingNothing; the error may go unnoticed.
Return a statusaddData(null) → falseNotices only if it looks at the return value.
Throw an exceptionthrow new IllegalArgumentException(...)If not caught, the program stops; the error is not lost.

The first approach is the simplest, but it hides the error. The caller thinks it wrote 75, yet the clock has not changed. The second approach reports the error, but it depends on the caller looking at the return value. A call that ignores the return value is as silent as in the first approach. The third approach makes the error impossible to ignore. The setSecond below throws an IllegalArgumentException for an invalid value:

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

s.setSecond(30) succeeds and the seconds become 30. In the call s.setSecond(75) the condition is true and the throw statement throws the exception. The assignment line does not run; the method ends at that point. The flow skips the rest of the try block, so "never reached" is not printed. Control passes to the catch block and the exception's message is printed. On the last line the seconds are still 30; the state of the object has not been corrupted.

Definition 4.2.4

An exception is an event that disrupts the normal flow while the program is running and is thrown as an object. The throw statement throws an exception object; an exception thrown in a try block is caught in the catch block that matches its type.

What happens if the exception is not caught? When the same setSecond(75) call is made outside a try, JDK 21 gives this output:

Exception in thread "main" java.lang.IllegalArgumentException: second must be 0-59: 75
	at DigitalClock.setSecond(DigitalClock.java:6)
	at Uncaught.main(Uncaught.java:4)

The first line of the message shows the type and message of the exception, and the following lines show where the exception was born. DigitalClock.java:6 is the line where the throw statement is; Uncaught.java:4 is the line where the faulty call was made. This is the strength of the exception: the faulty value becomes visible at the place where the call was made.

For argument errors in public methods, Java's customary choice is IllegalArgumentException. The Java library follows the same path. For example, Integer.parseInt("abc") throws a NumberFormatException, and this class is a subtype of IllegalArgumentException. Whichever approach is chosen, the choice must be documented as part of the contract. The user must be able to read from the documentation what the method will do with a bad argument.

4.2.2.4Writing the contract with Javadoc

Javadoc comments make it possible to write the contract in a form that is both readable and processable by tools. The comment starts with /**; the first sentence summarizes what the method does. The tags that follow state the parts of the contract separately:

/**
 * 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;
}
Table 4.2.4: Javadoc tags used to write the contract.
TagWhat is written?In the example
@paramEach parameter and its preconditionfor amount, 0 < amount <= balance
@returnThe return value, that is, the postconditionthe balance after the call
@throwsWhat happens when the contract is brokenIllegalArgumentException

The {@code ...} notation in the comment is not a mere detail. Javadoc processes the inside of comments as HTML. A raw < sign is taken to be the start of an HTML tag. When the same comment is written as 0 < amount <= balance without {@code}, the javadoc tool of JDK 21 gives two malformed HTML errors, and in the generated page an invalid input warning appears in place of the inequality. The text inside {@code ...}, on the other hand, is shown as it is, in a code font.

The command javadoc -d docs BankAccount.java produces HTML pages in the docs folder from these comments. The online documentation of the Java library is produced the same way. Every explanation read in the documentation of the String or Math class comes from the Javadoc comments in the source code of those classes.

The answer to the question of what to write in Javadoc comes from information hiding. What the method does and its conditions of use are written. How it does it is not written; that is the hidden implementation and it may change. The reader of Javadoc is the user who will never see the body. From this point of view, the outer face of a class is the sum of the signatures of the public methods and these comments.

The withdraw in the example enforces the contract with an exception. When tried with JDK 21 on an account with a balance of 1000 TL, withdraw(300.0) returns 700.0. withdraw(5000.0) and withdraw(-20) throw the exception with the messages Invalid amount: 5000.0 and Invalid amount: -20.0. Note the -20.0 in the second message: the argument -20 given as an int has been widened to the double parameter.

4.2.2.5Class invariants and assert

A precondition and a postcondition belong to a single method. Some rules, however, must hold at every moment for all objects of the class. The seconds of a clock must always be between 0 and 59, and the balance of a bank account must always be zero or positive.

Definition 4.2.5

A class invariant is a rule that the state of every object of a class must satisfy at all times. The invariant is established when the object is constructed and must be true again when each public method finishes.

To check an invariant during development, Java's assert statement is used. The statement assert condition : message; evaluates the condition; if the condition is false, it throws an AssertionError with the message. In the Counter class below an error has been left in on purpose: the value becomes 10 after 9, although the invariant requires the range 0–9.

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;
    }
}
public class Main {
    public static void main(String[] args) {
        Counter s = new Counter();
        for (int i = 0; i < 10; i++) s.increment();
        System.out.println("done");
    }
}

The program is run twice. First in the ordinary way, with the command java Main:

done

Then with assertions enabled, with the command java -ea Main:

Exception in thread "main" java.lang.AssertionError: value=10
	at Counter.increment(Main.java:5)
	at Main.main(Main.java:11)

The difference between the two outputs shows the most important property of assert. Assertions are disabled by default. If the -ea (enable assertions) option is not given, the assert line does not run at all; the condition is not even evaluated. The error passes silently and the program prints done. With -ea, on the tenth increment the value becomes 10, the condition comes out false and AssertionError: value=10 is thrown. The first line of the stack trace shows that the error was born in Counter.increment, on line 5 of the file Main.java.

This property also determines what assert is used for. assert checks, during development, internal assumptions about which the programmer says "this must never happen": class invariants, postconditions, code branches that should not be reached. The arguments of a public method, however, are not checked with assert. When assertions are off, no check is made and a faulty argument gets into the object. In short: an exception for arguments, assert for internal consistency.

Common mistake

Checking user input with assert. The line assert age >= 0; works only in a program run with -ea. When the program is run in the ordinary way, a negative age is accepted without any warning. For a value coming from outside, a check with if and IllegalArgumentException are used.

Common mistake

Writing an expression with side effects in an assert condition. A line such as assert list.remove(x); does not run at all when assertions are off; the element is not removed from the list. The behavior of the program changes with the -ea option. An assert condition only reads and changes nothing.

4.2.3Access modifiers

The "closing off" half of encapsulation is provided in Java by access modifiers. Who may use a field or method is determined by a single keyword written at the start of its declaration. The compiler enforces the rule; it is not left to the programmer's good intentions.

4.2.3.1public and private

Definition 4.2.6

An access modifier is a keyword that determines who can access a class, field or method. A public member can be accessed directly by other classes. A private member can be accessed only from inside the class; the compiler prevents access from outside.

The habit followed when writing a class can be summarized in three points. Classes are mostly declared public. The fields of the class are declared private. public methods are written to access and change the fields. In short: fields hidden, behaviors open.

public class Student {      // public class
    private String name;      // hidden field
    private int grade;        // hidden field

    public int getGrade() {   // public method
        return grade;
    }
}

In the Student class the fields name and grade are private. Another class cannot read the grade by writing o.grade; to read it, o.getGrade() is called. Figure 4.2.5 compares these two ways in UML notation. In UML class diagrams the sign - means a private member and + a public member.

Student- name : String (private)- grade : int (private)+ getGrade() : int (public)Other classo.getGrade() ✓o.grade ✗ error
Figure 4.2.5: Another class can call the public method getGrade() of Student (green arrow). An attempt to access the private field grade directly does not compile (red dashed arrow).

4.2.3.2The four access levels

Java has two further levels between public and private. Who each of the four levels is open to is given in Table 4.2.5.

Table 4.2.5: The four access levels. ✓ means accessible, ✗ means not accessible.
ModifierSame classSame packageSubclass (other package)Everywhere
public✓✓✓✓
protected✓✓✓✗
(none) package access✓✓✗✗
private✓✗✗✗

If no modifier is written, package access (package-private, called "default" in some sources) applies: only classes in the same package reach the member. protected is for subclasses. In addition to classes in the same package, subclasses in other packages also reach a protected member. A package is a group in which related classes are collected in the same folder. A subclass is a class derived from another class with extends. The levels form nested rings (Figure 4.2.6).

public: everywhereprotected: + subclasses in other packagespackage access: same packageprivate: same class
Figure 4.2.6: The access levels are nested regions. In the center is private (only the same class), and in the ring around it package access (the same package). Outside that is protected (plus subclasses in other packages), and at the outermost public (everywhere).

Every cell of the table has been tested with JDK 21. Four fields have been put in class A in package p1: public int pub, protected int prot, int pkg with no modifier, and private int priv. When an attempt is made to write to the four fields from four different places, the compiler gives these errors:

p1/B.java:3: error: priv has private access in A
    void tryIt(A a) { a.pub = a.prot = a.pkg = 1; a.priv = 1; }
                                                         ^
p2/C.java:3: error: pkg is not public in A; cannot be accessed from outside package
    void tryIt() { pub = prot = 1; pkg = 1; priv = 1; }
                                       ^
p2/C.java:3: error: priv has private access in A
    void tryIt() { pub = prot = 1; pkg = 1; priv = 1; }
                                                  ^
p2/D.java:3: error: prot has protected access in A
    void tryIt(p1.A a) { a.pub = 1; a.prot = 1; a.pkg = 1; a.priv = 1; }
                                     ^
p2/D.java:3: error: pkg is not public in A; cannot be accessed from outside package
    void tryIt(p1.A a) { a.pub = 1; a.prot = 1; a.pkg = 1; a.priv = 1; }
                                                     ^
p2/D.java:3: error: priv has private access in A
    void tryIt(p1.A a) { a.pub = 1; a.prot = 1; a.pkg = 1; a.priv = 1; }
                                                                  ^
6 errors

A's own method can write to all four fields; there is no error at all. B, in the same package, cannot reach only priv. The subclass C in another package cannot reach pkg and priv. The unrelated class D in another package can write only to pub. This result is exactly the same as the rows of the table. The messages also vary with the level: has private access, is not public in A; cannot be accessed from outside package and has protected access.

The rule for choosing the right level is simple: prefer the most restrictive level. First think of private; move to a more open level only if really needed. Opening a member later is easy and affects no one. Closing an open member later, on the other hand, breaks all the code that uses it.

A last rule concerns the classes themselves. A top-level class, that is, a class that is not inside another class, can be only public or package-private. When private class TopPrivate { } is written, the compiler gives the message modifier private not allowed here. private and protected classes can be defined only inside another class, as inner classes.

4.2.3.3Trying to access a private field

In the DigitalClock class the second field is private. What happens if another class tries to write to this field directly?

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

The message shows the file and line of the error (Test.java:4), its cause (second has private access in DigitalClock) and its position within the line (the ^ sign). The program never runs; no .class file is produced. Had the field been public, s.second = 75; would have been accepted silently and the clock would have fallen into an invalid state. The solution is to have the change made by the class's own method: s.setSecond(75);. The method rejects the invalid value (Figure 4.2.7).

TestDigitalClock- second = 0+ setSecond(int) rejects if not 0..59s.second = 75; compile errors.setSecond(75); runs, value rejected
Figure 4.2.7: The two ways of the Test class to DigitalClock. Writing to the field directly (s.second = 75;) is a compile error. Going through the setter (s.setSecond(75);) compiles and runs; but a value outside 0–59 is rejected and the field stays at 0.

The difference between the two ways is where the rule is checked. In the first way the compiler does the check and forbids access altogether. In the second way access is allowed, but the value goes through the class's own rule. Encapsulation uses both together: the direct way to the field is closed, and the checked way through the method is open.

4.2.3.4private works at class level

The word private does not mean "private to this object". Access control is done not per object but per class. The code of a class can read the private fields of every object created from that 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

The times method reads its own fields (num, den) and the fields of the other object that comes in as a parameter (other.num, other.den). The second object is another object, but of the same class; so access is free. The product of 2/3 and 3/4 is 6/12. The fraction is not simplified, because times only multiplies the numerators and denominators.

Thanks to this, methods that process two objects together, such as times, equals and compareTo, need no separate method to read a field. When the same line is written in another class, however, it does not compile:

Outside.java:3: error: num has private access in Ratio
        int p = new Ratio(1, 2).num;
                               ^
1 error

The limit of encapsulation is the source code of the class. The inside of the class is the responsibility of a single author, and that author knows all the rules of the class. What is protected is the users outside the class.

4.2.4Getter and setter methods

Once the fields are private, the only way to reach them is through the methods of the class. The two most common kinds of these methods are those that read the value of a field and those that change a field in a checked way.

Definition 4.2.7

An accessor (getter) is a method that returns the value of a field. A mutator (setter) is a method that first checks a new value for a field and assigns it if it is valid. In Java convention their names start with get and set.

4.2.4.1The DigitalClock class

The main example of the slides is a digital clock that keeps the hour, minute and second. The first version contains a getter and a setter only for the second:

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;
        }
    }
}

getSecond() returns the value of the field; it changes nothing. setSecond(int second) first checks the incoming value. If the value is between 0 and 59, the assignment is made; otherwise the method ends without doing anything. This setter has chosen the approach of silently ignoring. The UML diagram of the class is given in Figure 4.2.8.

DigitalClock- hour: int = 0- minute: int = 0- second: int = 0+ getSecond(): int+ setSecond(int): void
Figure 4.2.8: The UML diagram of the DigitalClock class. At the top the name of the class, in the middle the three private fields (-) and their initial values, at the bottom the two public methods (+) and their return types.

4.2.4.2Tracing the setter's protection

To see how the setter stops an invalid value, the program below is traced step by step:

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());
45
Table 4.2.6: Trace of the setSecond calls. Line numbers: 1–11 the class, 13–16 the calls in main.
StepLineCall stackVariablesNew output
113: DigitalClock s = new DigitalClock();main()s=→DigitalClock—
27: if (second >= 0 && second < 60) {main() → s.setSecond(45)this=→object, second=45—
38: this.second = second;main() → s.setSecond(45)this=→object, second=45—
47: if (second >= 0 && second < 60) {main() → s.setSecond(75)this=→object, second=75—
54: return this.second;main() → s.getSecond()this=→object, return=45—
616: System.out.println(s.getSecond());main()s=→DigitalClock45

In the first step the object is created and the second field starts at 0. In the second step setSecond(45) is called. There are two things in the new frame: the second parameter is 45 and this points to the object that called the method. The condition is true. In the third step this.second = second; runs. The this.second on the left is the object's field, the second on the right is the parameter; the field becomes 45.

The fourth step is the protection itself. In the call setSecond(75) the condition is false and the assignment line is skipped. The invalid value cannot enter the object. Figure 4.2.9 shows these two calls side by side. In the fifth step getSecond() returns the value of the field: 45. In the last step 45 is printed to the screen. The state of the object stayed valid from beginning to end.

StackHeapsetSecond(45)thissecond45main()sDigitalClocksecond045 ≥ 0 && 45 < 60 → true StackHeapsetSecond(75)thissecond75main()sDigitalClocksecond4575 < 60 → false
Figure 4.2.9: Two calls of the setter. Left, setSecond(45): the condition is true and the assignment will be made. Right, setSecond(75): the condition is false; the second field of the object on the heap stays at 45.

The cost of a getter and a setter is constant: one comparison, one assignment or one read. The Java virtual machine often inlines methods this small at run time; no measurable speed difference remains compared with direct field access. Encapsulation should not be seen as a cost that slows the program down.

4.2.4.3this and shadowing

In setters the name of the parameter is usually chosen to be the same as the name of the field: setSecond(int second). This choice improves readability, but it requires knowing a rule.

Definition 4.2.8

Shadowing is a name in an inner scope hiding the same name in an outer scope. If the name of a parameter is the same as that of a field, inside the method that name refers to the parameter; the field is left in the shade. this is a reference to the object that called the method, and this.second always refers to the field.

The correct form is this.second = second;. The Box class shows what happens when this is forgotten:

public class Box {
    private int width;
    public int getWidth() {
        return width;
    }
    public void setWidth(int width) {
        width = width;
    }
}

In the setWidth method both sides of the line width = width; are the parameter. The parameter is assigned to itself and the field never changes. After the call k.setWidth(5), k.getWidth() returns:

0

The field has stayed at 0, the default value of int fields. The most dangerous side of this error is that the compiler gives no error. width = width; is a valid Java statement. The error is noticed only when the program is run and the output is looked at. That is why the habit of writing this. in setters is important. Some development environments flag this line with a "self-assignment" warning, but javac with default settings stays silent.

Common mistake

Forgetting this with a final field. If the field is private final String name; and name = name; is written in the constructor, the result is different. The assignment is again made to the parameter; the field has been given no value. Because a final field must definitely be assigned in the constructor, the compiler this time gives the error variable name might not have been initialized, pointing at the end of the constructor. With a non-final field no warning appears at all.

4.2.4.4Access methods and naming

When a getter and a setter are written for all the fields of the clock, the class takes this form:

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

The first three calls are valid and the clock becomes 09:05:30. The call setHour(24) is rejected, because valid hours are 0–23. setMinute(-3) is rejected too. The second show() call therefore prints the same value. The %02d format in printf writes the number with at least two digits, adding a leading zero if needed: the value 9 appears as 09.

The names of access methods follow a convention. The getter of the minute field is called getMinute() and its setter setMinute(int). The first letter of the field name is capitalized and get or set is put in front. The getter of a boolean field, however, starts with is: isActive() for a field active. This convention is not only for readability. Many Java libraries and development tools derive the properties of a class from these names.

4.2.4.5Why not a public field?

Making a field private and writing two methods takes more effort than making it public. What this effort buys is summarized in Table 4.2.7.

public class Clock {
    public int second;
}
// in another class:
s.second = -5;   // accepted!
public class Clock {
    private int second;
    public void setSecond(int s) {
        if (s >= 0 && s < 60) second = s;
    }
}
Table 4.2.7: Comparison of the public field and the private field with methods.
Questionpublic fieldprivate field + methods
Who can write which value?Anyone, any valueOnly a value the method accepts
Where is the rule (0–59) checked?Left to every user; if one forgets, the object is corruptedIn a single place, inside the class
Is a read-only field possible?No (except with final)Yes; only the getter is written
If the name or type of the field changes?All the classes that use it changeThe signatures of the methods can stay the same

The last row of the table shows the longest-term gain: even when the internal structure changes, the signatures of the methods can be kept. When the two fields of the clock are reduced to a single totalSeconds field, the code that uses it does not change at all.

The interactive exercise in the slides makes this comparison on a DigitalClock object. The object is in the state 09:05:30. When one wants to write 75 to the seconds, two ways can be followed. The setter way (s.setSecond(75)) rejects the value and the clock stays at 09:05:30. Had the field been public (s.second = 75), the value would be written directly and the clock would show a meaningless state such as 09:05:75. The valid ranges are 0–23 for the hour and 0–59 for the minute and second.

For classes that only carry data and will never change, since Java 16 there is a shorter way: the record. The line record Point(int x, int y) { } defines a class whose fields are automatically private final. The names of the accessors do not start with get; they carry the name of the field: x() and y(). The compiler also writes the toString, equals and hashCode methods itself:

public class RecordTest {
  public static void main(String[] args) {
    Point n = new Point(3, 4);
    System.out.println(n.x() + " " + n.y());
    System.out.println(n);
    System.out.println(n.equals(new Point(3, 4)));
  }
}
3 4
Point[x=3, y=4]
true

An attempt to write to a record's field from outside (n.x = 5;) gives the error x has private access in Point. Because the field is both private and final, a record is a ready-made example of an immutable class.

4.2.5Example: a bank account

The pieces so far can be combined in a single class. A bank account is a good example for this: its data is valuable, its rules are clear and a breach of the rules is easily noticed. The balance must never fall below zero, and money must enter and leave only through certain operations. The BankAccount class is examined in four parts.

4.2.5.1Fields and constructor

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 of the class are private: the account number, the balance and the account type. No one can change the account number or the balance directly. The constructor builds the object with its initial values. Because the parameter names are chosen to be the same as the fields, the assignments are written with the this.balance = balance; pattern.

The class has only getters and no setter. The setBalance method has deliberately not been written. The balance changes only through deposit, withdrawal, interest and transfer operations. In this way every path that changes the balance passes through a method that enforces its own rule. There is no setter for the account number or the account type either; these two fields do not change after the account is opened.

4.2.5.2Deposit and withdrawal

  // ...
  // 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 the precondition. For a deposit the condition is amount > 0. For a withdrawal there are two conditions: amount > 0 and amount ≤ balance. If the condition is broken the balance does not change, only a message is printed. This class has chosen a path between "silently ignoring" and "reporting" when the precondition is broken: it throws no exception, but it prints on the screen what went wrong.

The order of the if–else if–else chain in withdraw matters. First the case in which the operation is valid is checked. If it is not valid, the first possible cause is that the amount exceeds the balance. The only case left is that the amount is zero or negative. Thanks to this arrangement every invalid call gets exactly one message.

Together, the two methods protect the class invariant: the balance cannot fall below zero by any route. A deposit only increases the balance; a withdrawal decreases it only if there is enough balance. If the invariant holds when the object is built, it stays true after these two methods as well.

4.2.5.3Interest

  // ...
  // 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 a savings account and with a positive rate. Because the account type is a text, the comparison is made with equals, not ==. == checks whether two references point to the same object; equals compares the contents of the texts. Two "Savings" texts created in two different ways may come out different with ==.

interest is a local variable. It exists only while the method runs and is not part of the object. The interest amount is computed once, added to the balance and vanishes when the method ends. Only the three fields make up the object's state.

4.2.5.4Transfer

  // ...
  // 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.");
    }
  }
}

The transfer method calls a method of another object of the same class: target.deposit(amount). It deducts from its own balance and adds to the target account with the deposit method (Figure 4.2.10).

acc1 objectbalance2000.0 → 1700.0acc2 objectbalance1500.0 → 1800.0target.deposit(300.0)transfer(acc2, 300.0): balance -= 300deposit's own rule: balance += 300
Figure 4.2.10: The two halves of a transfer. acc1 deducts 300 from its own balance. Then it calls the deposit method of the acc2 object; acc2 does the adding by its own rule.

It would also have been possible to write directly to the balance field of the target account: target.balance += amount;. The two objects are of the same class and private works at class level. But calling a method keeps the rules in one place. If a rule were added to deposits tomorrow, for example if every deposit were logged, the transfer would automatically pass through this rule too. Code that changed the field directly would skip the new rule.

4.2.5.5Tracing two accounts step by step

All the parts of the class are run with the main method below:

// 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());
500.0 TL deposited. New balance: 2500.0
200.0 TL withdrawn. New balance: 1300.0
Adding interest: 125.0 TL. New balance: 2625.0
300.0 TL deposited. New balance: 1600.0
300.0 TL transferred. New balance: 2325.0
2325.0
1600.0
Table 4.2.8: Trace of two bank accounts. The line numbers refer to the main fragment above (line 1 is a comment).
StepLineCall stackVariablesNew output
12: BankAccount acc1 =
3: new BankAccount(123456, 2000.0, "Savings");
main()acc1=→BankAccount—
24: BankAccount acc2 =
5: new BankAccount(789012, 1500.0, "Checking");
main()acc1=→BankAccount, acc2=→BankAccount—
36: acc1.deposit(500.0);main() → acc1.deposit(500.0)amount=500.0500.0 TL deposited. New balance: 2500.0
47: acc2.withdraw(200.0);main() → acc2.withdraw(200.0)amount=200.0200.0 TL withdrawn. New balance: 1300.0
58: acc1.addInterest(5.0);main() → acc1.addInterest(5.0)rate=5.0, interest=125.0Adding interest: 125.0 TL. New balance: 2625.0
69: acc1.transfer(acc2, 300.0);main() → acc1.transfer(acc2, 300.0)amount=300.0, target=→acc2—
79: acc1.transfer(acc2, 300.0);main() → acc1.transfer(acc2, 300.0) → acc2.deposit(300.0)amount=300.0300.0 TL deposited. New balance: 1600.0
89: acc1.transfer(acc2, 300.0);main() → acc1.transfer(acc2, 300.0)amount=300.0300.0 TL transferred. New balance: 2325.0
910: System.out.println(acc1.getBalance());
11: System.out.println(acc2.getBalance());
main()acc1=→BankAccount, acc2=→BankAccount2325.0 ⏎ 1600.0

In the first two steps two independent objects are built. Each object has its own balance field: acc1's is 2000.0 and acc2's is 1500.0. In the third step acc1.deposit(500.0) is called. In this call this points to acc1; amount > 0 is true and the balance becomes 2500.0. In the fourth step this is acc2 this time. Because 200 ≤ 1500, the withdrawal is made and the balance drops to 1300.0. acc1 is not affected by this operation.

In the fifth step the interest is computed. The account is a savings account and the rate is positive: interest = 2500.0 × 5 / 100 = 125.0. The balance becomes 2625.0. In the sixth step the transfer begins. The condition is true; acc1 first deducts from its own balance: 2625.0 − 300.0 = 2325.0. In the seventh step target.deposit(amount) is called. There are now three frames on the stack: main, transfer and deposit. In this topmost frame this points to acc2 and its balance becomes 1600.0 (Figure 4.2.11).

StackHeapmain()acc1acc2BankAccountthisaccountNumber123456balance2325.0accountType"Savings"BankAccounttargetaccountNumber789012balance1300.0accountType"Checking" StackHeapmain()acc1acc2BankAccountaccountNumber123456balance2325.0accountType"Savings"BankAccountthisaccountNumber789012balance1600.0accountType"Checking"
Figure 4.2.11: Two moments inside the transfer. Left: transfer is running; this points to the first account and target to the second; the balance of the first account has dropped to 2325.0. Right: deposit is running; this time this is the second account and its balance is 1600.0.

In the eighth step deposit ends and transfer continues where it left off. Note the order in the output: first "300.0 TL deposited" (the message of the inner call), then "300.0 TL transferred" (the message of the outer method) is printed. In the last step the getters read the two balances. The total money has been preserved: 2325 + 1600 = 3925 = 2625 + 1300. A transfer produces no money, it only moves it.

Every method of the class does a constant number of operations; there are no loops. So the time cost of each call is O(1). In memory each account object holds only three fields; as the number of objects grows, memory grows linearly.

The numbers in the output are the default Java form of double values: 500.0, 2625.0. In this example all the amounts are whole numbers, so no problem arises. But double cannot always hold decimal fractions exactly. When 0.2 TL is deposited into an account with a balance of 0.1 TL using the same class, JDK 21 prints New balance: 0.30000000000000004. Real banking software therefore keeps money as an integer number of cents or with the BigDecimal class.

4.2.5.6A constructor that validates too

The operation methods of BankAccount protect the balance. But its constructor assigns the incoming values without checking them at all. This gap can be abused in two ways. new BankAccount(1, -500.0, "Checking") builds an account with a negative balance; the invariant is already broken as the object is born. If "savings" (in lowercase) is written, the account can never receive interest and no one notices. When tried with JDK 21, both objects are built without trouble; when addInterest(5.0) is called on the lowercase account, the message "Interest applies only to savings accounts." appears.

The class invariant must hold at the moment the object is born. The constructor is also a precondition checker:

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;
}

With this constructor, the call new BankAccount(1, -500.0, "Checking") throws an exception with the message Initial balance cannot be negative, and the call new BankAccount(2, 1000.0, "savings") with the message Unknown account type: savings. If null is given as the account type, the call accountType.equals(...) throws a NullPointerException; that also prevents the object from being built, but its message is less descriptive.

If the constructor throws an exception, the new expression produces no reference. The invalid object never reaches the user. This behavior can be followed with a small Temperature class:

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);
Rejected: Kelvin cannot be negative
300.0 null
Table 4.2.9: Trace of validation in the constructor. Line numbers: 1–10 the Temperature class, 12–20 the code in main.
StepLineCall stackVariablesNew output
112: Temperature a = new Temperature(300);main()a=→#1—
213: Temperature b = null;main()a=→#1, b=null—
315: b = new Temperature(-5);
3: public Temperature(double kelvin) {
main() → Temperature(-5.0)a=→#1, b=null, kelvin=-5.0—
44: if (kelvin < 0)
5: throw new IllegalArgumentException(
main() → Temperature(-5.0)a=→#1, b=null, kelvin=-5.0—
516: } catch (IllegalArgumentException e) {
17: System.out.println("Rejected: "
18: + e.getMessage());
main()a=→#1, b=nullRejected: Kelvin cannot be negative
620: System.out.println(a.getKelvin() + " " + b);main()a=→#1, b=null300.0 null

In the first step 300 is valid; the condition is false, kelvin is assigned and a points to the new object. In the second step b is explicitly initialized with null. This assignment is necessary: b will be read after the catch block. Java does not allow a local variable that might not have a value to be read.

In the third step new allocates the second object and calls the constructor. The kelvin field of the allocated object is 0.0, the default value; the parameter is −5.0. In the fourth step the precondition is found broken and throw cuts the constructor short. The assignment line never runs. Figure 4.2.12 shows these two moments.

StackHeapTemperature(kelvin)kelvin-5.0main()abnullTemperature #1kelvin300.0Temperature #2kelvin0.0half-builtnew allocated; constructor runs StackHeapmain()abnullTemperature #1kelvin300.0Temperature #2kelvin0.0left for the GCno assignment: b is still null
Figure 4.2.12: Validation in the constructor. Left: new has allocated the second object and the constructor is running with the parameter −5.0; the object is half-built. Right: the exception has been caught, the assignment b = ... was never made; b is still null and no reference points to the half-built object.

In the fifth step control passes to the catch block and Rejected: Kelvin cannot be negative is printed. Because the assignment b = new Temperature(-5); was cut short, b has not changed. No reference reaches the half-built object; the garbage collector cleans it up after a while. In the last step 300.0 null is printed. Only valid Temperature objects can be used in the program: the invariant (kelvin ≥ 0) is true for every object.

The constructor is the single door through which an object is built. If the rules are enforced there once, the other methods of the class can trust that the object they receive is valid. In classes that have setters, it is also a common practice for the constructor to call the setter instead of rewriting the same check. That way the rule stays in a single method.

Common mistake

Validating the setters and forgetting the constructor. setSecond rejects 75, but if the constructor writes this.second = second;, then new DigitalClock(75) builds an invalid clock. Every path by which a value enters the object, the constructor included, must pass through the same rule.

4.2.6Class design

An encapsulated class has two faces: the outer face the user sees and the internal structure only the author knows. This distinction guides most of the decisions made when designing a class. This section defines the distinction as a concept, makes it concrete with Java's interface construct, and shows how a class can change its internal structure without breaking its users.

4.2.6.1Interface and implementation

Definition 4.2.9

A class definition is divided into two parts. The interface states what the class does and how it is used: the names, parameters, return types and comments of the public methods. The implementation contains the internal mechanical details of the class and its private fields; these matter only inside the class.

Even if the implementation changes, the interface may stay the same, because private fields are hidden from outside the class. Some sources describe this distinction with three elements. The specification is the signatures of the constructor and methods. The representation is the private fields that hold the data. The implementation is the bodies of the constructor and methods. The user knows only the specification. Even if the representation and implementation change, the user's code does not break.

An espresso machine shows this distinction well (Figure 4.2.13). The user knows the "Start", "Water amount" and "Stop" buttons on the control panel. The pump, boiler, valves and brew group are behind the panel. Even if the manufacturer replaces the pump with a quieter model, the panel stays the same and the user notices the difference only from the sound.

UserControl panel(interface)StartWater amountStopInside (implementation)PumpBoiler, heaterFlow valveSolenoid valveBrew group
Figure 4.2.13: The espresso machine analogy. The user uses only the control panel (the interface); the pump, boiler and heater, the flow and solenoid valves and the brew group are the internal mechanism (the implementation).

4.2.6.2interface and implements

Java has set aside a language construct for the idea of an interface. A type declared with the interface keyword is a contract that says what a class will do. The methods have only a signature, no body:

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

    public void stop();
}

The methods in an interface are implicitly public and abstract; the meaning does not change if the public words in the example are left out. The person driving the car knows only the methods drive() and stop(). The class that implements the interface writes how the job is done:

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/sa");
  }

  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.

The phrase implements Car says that SportsCar implements the Car interface. This is a promise, and the compiler checks whether the promise is kept: the class must write every method in the interface. Figure 4.2.14 shows the relation between the two types in UML.

«interface»Car+ drive(): void+ stop(): voidimplementsSportsCar- brand: String- speed: int+ SportsCar(brand: String)+ drive(): void+ stop(): void
Figure 4.2.14: In UML notation the SportsCar class implements the Car interface. The dashed line with an empty triangle is the "implements" relation. The interface has only two public methods; the class additionally has two private fields and a constructor.

An interface and a class cannot have the same name in the same package. If one tries to give the class the name Car too, the compiler gives the error duplicate class: Car; that is why the class is named SportsCar. The main method declares its variable with type Car: Car car = new SportsCar("Rüzgar");. This code therefore depends only on the interface. If another implementation were used in place of SportsCar tomorrow, only the new expression would change.

What happens if a method is not written? If SportsCar writes only drive() and forgets stop(), JDK 21 gives this message:

MissingMethod.java:5: error: SportsCar is not abstract and does not override abstract method stop() in Car
class SportsCar implements Car {
^
1 error

The message also names both ways out: either the class writes the missing method or it is itself marked abstract. What matters here is that the interface turns the "outer face" idea of encapsulation into a construct the compiler checks.

4.2.6.3Changing the implementation

The strongest gain of encapsulation is being able to change the internal structure of a class without breaking its users. DigitalClock is written in two versions to show this. The old version keeps the minute and the second in 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;
    }
  }
}

The new version uses a single field: the number of seconds since midnight. The minute and second are no longer stored; they are computed from this number every time they are asked for:

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();
    }
  }
}

The public methods of the two versions are the same: getMinute(), getSecond(), setMinute(int), setSecond(int). The code that uses them cannot tell which one it is working with. The computations in the new version need a little thought. totalSeconds / 60 gives the total number of minutes; % 60 separates its minute part within the hour. totalSeconds % 60 is the second part. The setters cannot write the new value directly, because they must preserve the other part. Instead they add the difference between the old value and the new value.

The usage code below is traced step by step with the new version:

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());
Table 4.2.10: Trace of the single-field DigitalClock. Line numbers refer to the shortened code above: 1–9 are fragments of the class, 10–16 are main.
StepLineVariablesNew output
110: DigitalClock s = new DigitalClock(); // maintotalSeconds=0—
211: s.setMinute(12);totalSeconds=720—
312: s.setSecond(45);
5: public void setSecond(int second) {
6: if (second >= 0 && second < 60)
second=45, totalSeconds=720—
47: totalSeconds += second - getSecond();
2: public int getSecond() {
3: return totalSeconds % 60;
second=45, getSecond()=0, totalSeconds=765—
513: s.setSecond(75);
6: if (second >= 0 && second < 60)
second=75, totalSeconds=765—
614: s.setSecond(9);
7: totalSeconds += second - getSecond();
second=9, getSecond()=45, totalSeconds=729—
715: System.out.println(s.getMinute() + ":"
16: + s.getSecond());
getMinute()=12, getSecond()=912:9

At the start totalSeconds is 0; to an outside observer the clock reads 00:00. In the call setMinute(12), getMinute() returns 0, the difference is 12 minutes and 12 · 60 = 720 seconds are added. The old version would have written just minute = 12 in the same call. In the call setSecond(45), first getSecond() = 720 % 60 = 0 is computed; the difference is 45 and the total becomes 765. To an outside observer the clock reads 12:45.

The call setSecond(75) is rejected in both versions; the rule (0–59) has stayed inside the class. In the call setSecond(9) the difference is negative: 9 − 45 = −36. The total becomes 765 − 36 = 729 and the minute part is still 12. Figure 4.2.15 shows these two moments together with the two versions.

StackHeapmain()sNew versiontotalSeconds765getMinute()12getSecond()45Old versionminute12second45720 + (45 − 720 % 60) = 720 + 45 = 765 StackHeapmain()sNew versiontotalSeconds729getMinute()12getSecond()9Old versionminute12second9765 + (9 − 45) = 729
Figure 4.2.15: The same interface, two implementations. In the upper box of each drawing is the single field of the new version (totalSeconds) and the values computed from it; in the lower box are the two fields of the old version. Left: after setSecond(45) (765 ↔ 12 and 45); right: after setSecond(9) (729 ↔ 12 and 9).

The last line prints 12:9; the old version would have given the same. When the two versions are run side by side with the same calls on JDK 21, the same minute and second values are found at every step: 12:45 and 12:9. The internal representation changed, and not a single letter of main changed. The notation 12:9 in the output is because no formatting is applied; with printf("%d:%02d", ...) one gets 12:09.

This change has a price too. In the old version getMinute() reads just a field. In the new version it does a division and a remainder operation. Both are O(1); the difference is negligible. But the setters now call the getter first. The designer can make such trade-offs without reflecting them to the user at all. This is the freedom encapsulation provides.

4.2.6.4Design advice

Four pieces of advice are followed when writing an encapsulated class:

  1. All the fields in the class are declared private.
  2. As many public methods as necessary are provided to access the fields. It is not obligatory to write a setter automatically for every field.
  3. Comments are written saying how each method is to be used: what it does and what its preconditions and postconditions are.
  4. Helper methods used only inside the class are declared private.

The fourth piece of advice is a reminder that encapsulation applies to methods as well as to fields:

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;
    }
}

isValid is an internal matter of the class. setGrade uses it, but there is no reason to expose it. When o.isValid(50) is called from another class, the compiler gives this error:

Outside.java:4: error: isValid(int) has private access in Student
        boolean b = o.isValid(50);
                     ^
1 error

Keeping the helper method private keeps the outer face of the class small. Every method on the outer face is a promise and cannot be taken back later. A private method, on the other hand, is a detail that the author can change or delete whenever they like.

4.2.6.5Tell, 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 merely been moved one step away. The two code fragments below show the difference. In the first, the code that uses the object asks the object for its data and makes the decision itself:

// 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));

In this form the rule is repeated in every place that uses the object. If one place forgets it, the object is corrupted. Moreover, as soon as setBalance is written, anyone can set the balance to any value they want; the class's invariant is left unprotected. In the second form the code that uses the object tells it what is wanted:

h.withdraw(300);   // rule in BankAccount
o.addBonus(5);     // 100 cap in Student

The decision is made by the object that holds the data. BankAccount decides whether a 300 TL withdrawal will be made; Student ensures that the grade does not exceed 100. A setter is written only where the field can truly change freely. That is why BankAccount has no setBalance.

A simple question is enough to find out where a method belongs: "Who has the data needed to make this decision?" If the answer is the object itself, the decision should also be in its method.

4.2.6.6The gains of encapsulation

The examples in these notes up to here have shown the four gains of encapsulation concretely:

  • Abstraction. The relation between the object and its user becomes simpler; the user knows only the methods. service.addData("Ayşe") is a single line.
  • Protection. The object is protected against unwanted or faulty access by users. s.second = 75; does not compile, and setSecond(75) is rejected.
  • Changeability. The internal structure of the class can be changed without changing the interface; the code that uses it is not affected. The two-field clock turned into a single-field clock and main stayed the same.
  • Valid state. The state of the object always obeys the rules. Only points with positive coordinates, seconds and minutes between 0 and 59, non-negative hours or balances. withdraw never lets the balance fall below zero.

The large-scale result of these gains is seen in Figure 4.2.16. A program may have many classes that use BankAccount: banking operations, reports, tests. All of them depend only on the interface.

BankReportTestInterfacepublic methodsdeposit()withdraw()getBalance()stableImplementationprivate fieldsbalancehelper methodscan change
Figure 4.2.16: The direction of dependency. The Bank, Report and Test classes depend only on the interface (deposit(), withdraw(), getBalance()); the interface is stable. The implementation (private fields and helper methods) is behind the interface and may change.

Interfaces change much more rarely than implementations; this keeps the code stable. When an implementation changes, the code that depends on it directly has to change too. Hiding the implementation removes this dependency and the change stays inside the class. This situation is called loose coupling. In a loosely coupled program, changing one class does not require touching the others.

4.2.7Immutable classes

Making fields private and writing no setters does not mean encapsulation is complete. If a field points to a mutable object such as an array or a list, the reference to that object can leak out. This section explains how the leak arises, how it is closed, and why objects that never change solve this problem from the start.

4.2.7.1A leaked reference

The ReportCard class keeps the grades in an array. The field is private final and there is no setter. At first sight the grades look protected:

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 grades have been changed from outside; moreover an invalid grade like −100 has got in. The reason is that an array is an object. The constructor and the getter share not the array but only its reference. The same array can be reached from three places: from the variable arr in main, from the field of ReportCard and from the reference the getter returns. Table 4.2.11 shows step by step how this situation arises.

Table 4.2.11: Trace of the leaked reference. Line numbers: 1–6 the constructor and getter of ReportCard, 8–12 main.
StepLineCall stackVariablesNew output
18: int[] arr = {70, 80, 90};main()arr=→[70, 80, 90]—
29: ReportCard k = new ReportCard(arr);
2: this.grades = grades;
main() → ReportCard(grades)arr=→[70, 80, 90], k=→ReportCard—
310: arr[0] = 0;main()arr=→[0, 80, 90], k=→ReportCard—
411: k.getGrades()[1] = -100;
5: return grades;
main()arr=→[0, -100, 90], k=→ReportCard—
512: System.out.println(k.average());main()arr=→[0, -100, 90], k=→ReportCard-3.3333333333333335

In the first step the array is created on the heap; the variable arr holds only its reference. In the second step the constructor writes the reference in the parameter to the field. Now the private field of ReportCard and the variable arr of main point to the same array. The constructor has copied the reference, not the array.

In the third step arr[0] = 0 runs. This line does not pass through any method of ReportCard, yet the grade that ReportCard sees changes. In the fourth step getGrades() returns the inner array itself and −100 is written through the returned reference. An invalid grade has got into the object without passing any check (Figure 4.2.17).

StackHeapReportCard(grades)gradesmain()arrk?int[3][0]70[1]80[2]90ReportCardgradesconstructor copied the reference StackHeapmain()arrkint[3][0]0[1]-100[2]90ReportCardgradesgetter leaked the inner reference
Figure 4.2.17: A leaked reference. Left: the constructor is running; the grades parameter and the field of ReportCard point to the same int[3] object as arr in main. Right: the getter has handed out the reference of the inner array and −100 has been written to cell [1].

In the last step the average (0 − 100 + 90) / 3 ≈ −3.33 is found. Java prints this value as -3.3333333333333335; the 5 in the last digit comes from the binary representation of double. Writing private was not enough: the reference to the inner object leaked out.

The word final does not prevent this either. final only prevents the reference from pointing to another array; it does not protect the contents of the array. Inside the class grades[0] = 0; compiles without trouble, whereas grades = new int[2]; gives the error cannot assign a value to final variable grades. What does not change is the reference in the box, not the object the reference points to.

4.2.7.2Defensive copying

Definition 4.2.10

A defensive copy is copying a mutable object as it enters the class and as it leaves the class. The only reference that reaches the inner object remains the class's own field.

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 method this version prints:

80.0

The grades.clone() in the constructor protects against the caller changing the array it holds afterwards. arr[0] = 0 now changes only the array of main; the copy of ReportCard stays at 70. The copy in the getter protects against the returned array being changed. k.getGrades()[1] = -100 writes to a temporary copy, and that copy is lost immediately. The average is (70 + 80 + 90) / 3 = 80.0.

For lists there are two options. new ArrayList<>(list) produces an independent copy. Collections.unmodifiableList(list) does not copy; it gives a read-only view of the same list. The difference between the two can be seen with JDK 21 as follows:

import java.util.*;
public class Lists {
  public static void main(String[] args) {
    List<Integer> inner = new ArrayList<>(List.of(70, 80));
    List<Integer> view = Collections.unmodifiableList(inner);
    List<Integer> copy = new ArrayList<>(inner);
    inner.add(90);
    System.out.println(view + " " + copy);
    try {
      view.add(100);
    } catch (UnsupportedOperationException e) {
      System.out.println(e.getClass().getName());
    }
    List<Integer> fixed = List.copyOf(inner);
    inner.set(0, 0);
    System.out.println(fixed + " " + view);
  }
}
[70, 80, 90] [70, 80]
java.lang.UnsupportedOperationException
[70, 80, 90] [0, 80, 90]

After 90 is added to the inner list, the view shows [70, 80, 90] and the copy shows [70, 80]. The view reflects the changes of the inner list; only changes through the view cannot be made. view.add(100) throws an UnsupportedOperationException. List.copyOf, available since Java 10, produces an unmodifiable copy: when the first element of the inner list is made 0, the copy is not affected.

Immutable objects such as String and Integer are not copied. Since there is no way to change them, sharing them is harmless. Copying also has a cost: a copy of an array of n elements needs O(n) time and O(n) extra memory. Because a copy is produced every time the getter is called, this cost accumulates for large arrays that are called often. In such cases a read-only view or an immutable type from the start is cheaper.

4.2.7.3Designing an immutable class

Definition 4.2.11

An immutable object is one whose state never changes after it has been created. String is the best-known example.

The way to solve the leaked reference problem at the root is for the object never to change. The Money class below keeps the amount as a long in cents:

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;
    }
}

An immutable class obeys five rules:

  1. There are no setters; the state is established only in the constructor.
  2. The fields are private final.
  3. The class is final, so a mutable subclass cannot be written.
  4. Methods that "change" do not modify the object but return a new one.
  5. If there are mutable fields, a defensive copy is made.

The compiler supports every rule as well. When an attempt is made to assign a value to a final field outside the constructor, for example when cents += k; is written, the error cannot assign a value to final variable cents appears. An attempt to derive from a final class gives the error cannot inherit from final Money. The third rule may seem unnecessary. But if a subclass could be written, that subclass could add its own mutable fields and be used in place of Money.

The gains of an immutable class are large. The invariant is checked only in the constructor; afterwards it can never be broken. The object can be shared without copying; no defensive copy is needed. It can safely be used as a key in structures such as HashMap, because the key cannot change and lose its place in the table. It is also safe between threads; two threads reading the same object cannot disturb each other. String and record are ready-made examples of these rules.

The toString method writes the amount in lira and kuruş: cents / 100 gives the whole-lira part and cents % 100 the kuruş part. String.format("%02d", ...) pads the kuruş to two digits; 5 kuruş appears as 0.05 TL. This notation breaks for negative amounts: new Money(-50, "TL") prints 0.-50 TL, because −50 / 100 = 0 and −50 % 100 = −50. If the class is to allow negative amounts, toString has to handle this case separately.

4.2.7.4Tracing the Money class

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);
Table 4.2.12: Trace of immutable Money objects. Line numbers: 1–6 the plus method, 8–11 main.
StepLineCall stackVariablesNew output
18: Money a = new Money(1250, "TL");main()a=12.50 TL—
29: a.plus(new Money(100, "TL")); // result lost
5: return new Money(cents + other.cents, unit);
main() → a.plus(other)a=12.50 TL—
39: a.plus(new Money(100, "TL")); // result lostmain()a=12.50 TL—
410: Money b = a.plus(new Money(375, "TL"));
5: return new Money(cents + other.cents, unit);
main()a=12.50 TL, b=16.25 TL—
511: System.out.println(a + " | " + b);main()a=12.50 TL, b=16.25 TL12.50 TL | 16.25 TL

In the first step the first object is built: 1250 kuruş, that is, 12.50 TL. Because its fields are final, no method can change them from now on. In the second step a.plus(new Money(100, "TL")) is called. A second object (#2) is built as the argument. plus does not change a; it builds a new object (#3) carrying the sum and returns it.

The third step shows the most frequent mistake. The returned value has not been assigned to a variable; #3 is lost and a has not changed (Figure 4.2.18). The compiler gives no warning for this line; ignoring the result of a method that returns a value is allowed in Java. In the fourth step the result is assigned to b: 1250 + 375 = 1625 kuruş. The #4 built as the argument is no longer used either. In the last step a has kept its first value.

StackHeapmain()ab?Money #1cents1250unit"TL"Money #2cents100Money #3cents1350result unassigned: losta still 12.50 TL StackHeapmain()abMoney #1cents1250unit"TL"Money #5cents1625unit"TL"two unchanging objects
Figure 4.2.18: Immutable objects. Left: the result of plus has been discarded: no variable is attached to object #3 (1350 kuruş), and a is still 12.50 TL. Right: the end of the program; a points to 1250 kuruş and b to 1625 kuruş; two separate, unchanging objects.
12.50 TL | 16.25 TL

The methods of String work the same way. The trial below also shows the other behaviors of the Money class:

public class MoneyDemo {
  public static void main(String[] args) {
    String s = "java";
    s.toUpperCase();
    System.out.println(s);
    s = s.toUpperCase();
    System.out.println(s);
    Money a = new Money(1250, "TL");
    try {
      a.plus(new Money(100, "USD"));
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }
    System.out.println(new Money(5, "TL") + " " + new Money(-50, "TL"));
  }
}
java
JAVA
Units differ
0.05 TL 0.-50 TL

s.toUpperCase(); on its own does not change s, and java is printed; when s = s.toUpperCase(); is written, JAVA is obtained. Adding different units is rejected with the message Units differ. The last line shows that toString prints 5 kuruş correctly and −50 kuruş wrongly. The correct pattern is always the same: a = a.plus(p);.

Common mistake

Taking a method of an immutable object for a mutator. Lines such as a.plus(p);, s.toUpperCase(); and s.trim(); change nothing on their own. The method returns a new object, and if the result is not assigned, it is lost. The compiler does not warn; the error is seen only in the output.

4.2.8Packages

Encapsulation does not stop at the boundary of a single class. A large program consists of hundreds of classes, and some of these classes serve only a few neighboring classes. Packages group classes, prevent name clashes and build a second layer of encapsulation one level above the class.

4.2.8.1Packages and folders

Definition 4.2.12

A package is a collection of classes grouped in a folder; the name of the folder is the name of the package. Which package a file belongs to is stated by the package package_name; declaration on the first line of the file.

Several rules apply when working with packages. Every public class is defined in a separate file, in a file with the same name as the class. The package declaration is the first line of the file; only comments may come before it. In nested folders a dot is used instead of / or \: the folder school/admin is the package school.admin. Package names are written in lowercase. Java's own packages are named this way too: java.lang, java.util, java.io.

The project structure below has two packages. The bank package contains the account work and the app package the entry point of the program. The source files are under src/ and the compiled files under out/:

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

The full name of a class includes its package: bank.Account, app.Main. The compiler and the Java virtual machine look for packages starting from the roots of the classpath. The package name gives the folder path from this root: the class bank.Account is the file bank/Account.class under the root. The default classpath is the folder in which the command is run (.).

Common mistake

Writing a public class in a file with a different name. When public class Account is written in the file Bank.java, the compiler gives the error class Account is public, should be declared in a file named Account.java. The file name must be exactly the same as the name of the public class, including case.

4.2.8.2Compiling and running a packaged program

Let us write a small program with two packages. The bank.Account class does deposits and balance reading; app.Main uses this class:

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 h = new Account();
        h.deposit(250.0);
        System.out.println("Balance: " + h.getBalance());
    }
}

To be able to use Account from another package by its short name, Main writes the line import bank.Account;. In the project folder the compile and run commands are:

> javac -d out src/bank/Account.java src/app/Main.java
> java -cp out app.Main
Balance: 250.0

The -d out option writes the .class files under out/ together with the package folders. When run with JDK 21, the files out/bank/Account.class and out/app/Main.class are produced. The Helper.class shown in the project structure appears only if Helper.java is also added to the compile command. -cp out sets the classpath to the out folder. When running, not the file path of the class but its full name is given: app.Main.

This distinction is the point where beginners get stuck most often. When wrong commands are tried in the same project, JDK 21 gives these messages:

Table 4.2.13: Attempts to run the packaged class app.Main (in the project folder, JDK 21).
CommandResultWhy
java -cp out app.MainBalance: 250.0Classpath and full name are correct.
java -cp out MainClassNotFoundException: MainThe package name is missing; there is no Main.class at the root.
java -cp out/app MainNoClassDefFoundError: Main (wrong name: app/Main)The file was found, but the class inside it is named app.Main.
java -cp out/app Main.classClassNotFoundException: Main.classThe file name was given instead of the class name.

The message on the third row is instructive. Java finds the file Main.class, but the class inside the file introduces itself as app.Main. Because the package name does not match the folder structure, the class is not loaded. A package is not only a folder; it is a part of the class's name.

4.2.8.3Importing (import)

Definition 4.2.13

An import is a declaration that makes it possible to use a class from another package by its short name. import package_name.ClassName; imports a single class, and import package_name.*; imports all the classes in the package.

import is not mandatory; a class can always be written with its full name: java.util.Random. import only shortens the long name. Some classes need no import at all. Classes in the java.lang package (String, Math, System, Integer) and classes in the same package are visible automatically in every file.

In a source file the order is fixed: first package, then the imports, and last the class. The import static form lets a static member of a class be used without writing the class name. The program below shows the three ways together:

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));
  }
}

When 49 is given as input, the output is:

7.0 49 30

Scanner is used by its short name thanks to import java.util.Scanner;. java.util.Random, on the other hand, is written with its full name without being imported. sqrt is called without writing Math. thanks to import static java.lang.Math.sqrt;; the square root of 49 is 7.0. Math.max needs no import because it comes from java.lang, and it gives the larger of 49 and 10. The last number is the first nextInt(100) value of a random number generator started with seed 42. Because the same seed produces the same sequence on every run, this value is always 30.

When import is forgotten, the compiler does not recognize the class. In a file that uses Scanner without importing it, JDK 21 gives a separate error for each of the two occurrences of Scanner in the line:

ScannerMissing.java:3: error: cannot find symbol
        Scanner sc = new Scanner(System.in);
        ^
  symbol:   class Scanner
  location: class ScannerMissing
ScannerMissing.java:3: error: cannot find symbol
        Scanner sc = new Scanner(System.in);
                            ^
  symbol:   class Scanner
  location: class ScannerMissing
2 errors

The fix is to add import java.util.Scanner; at the top of the file. import is only a compile-time convenience; it does not slow the program down and puts no extra code in the .class file. Writing import java.util.*; also does not "load" all the classes in the package into the program; it only tells the compiler where to look for names.

4.2.8.4Package access

Classes and members written without an access modifier are package-private: they are visible only from their own package. This rule applies to classes as well. The Helper class in the bank package is not public:

package bank;

class Helper {     // not public
    static double vat(double amount) {
        return amount * 0.20;
    }
}
package app;

import bank.Helper;

public class Main2 {
}
app/Main2.java:3: error: Helper is not public in bank; cannot be accessed from outside package
import bank.Helper;
            ^
1 error

Helper is an internal matter of the bank package. Account in the same package can use it; the app package cannot. A package thus also becomes a level of encapsulation. Classes are closed off from the outside; only the public ones make up the outer face of the package. Just as a class hides its inside with private fields, a package hides its inside with non-public classes.

To make a class usable from outside the package, making the class public may not be enough. The constructors and methods used must also be public. If the school.Student class has been made public but the getName() method has been left without a modifier, the call o.getName() from the app package gives the error getName() is not public in Student; cannot be accessed from outside package.

4.2.8.5Package naming and subpackages

Millions of Java classes have been written in the world, and a simple package name such as bank can easily clash with someone else's. To prevent clashes, organizations begin the package name with their reversed domain name. Because the domain name of Giresun University is giresun.edu.tr, the package name becomes tr.edu.giresun.bank. Dotted names correspond to folders: tr/edu/giresun/bank/.

Names looking nested grants no access right. A subpackage is a separate package. The package tr.edu.giresun.bank.report cannot see the package-private members of the package tr.edu.giresun.bank:

// 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); }
}
tr/edu/giresun/bank/report/Report.java:3: error: Helper is not public in tr.edu.giresun.bank; cannot be accessed from outside package
import tr.edu.giresun.bank.Helper;
                           ^
tr/edu/giresun/bank/report/Report.java:5: error: Helper is not public in tr.edu.giresun.bank; cannot be accessed from outside package
    double compute() { return Helper.vat(100); }
                              ^
2 errors

The same rule applies to import. import tr.edu.giresun.bank.*; does not import subpackages. import java.util.*; likewise does not bring in the classes of the java.util.function package. When the Function interface is to be used, the compiler cannot find the class:

FunctionMissing.java:5: error: cannot find symbol
        Function<Integer, Integer> f = x -> x * 2;
        ^
  symbol:   class Function
  location: class FunctionMissing
1 error

The fix is to write the line import java.util.function.Function; separately. If the package name and the folder path do not match exactly, the compiler and the virtual machine cannot find the class. Development environments therefore create the folders from the package name themselves.

4.2.8.6Class name clashes

Two classes in different packages can have the same name. A well-known example in the Java library is java.util.Date and java.sql.Date. If both packages are imported with *, the name Date becomes ambiguous:

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
        Date date = null;
        ^
  both class java.sql.Date in java.sql and class java.util.Date in java.util match
1 error

The compiler finds both classes and cannot choose which one is meant. To resolve the ambiguity the package name is used. One is imported with a single-class import and the other is written with its full name:

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

A single-class import java.util.Date; takes precedence over imports made with *. Date now means only java.util.Date. new Date(0) builds the object denoting midnight on 1 January 1970 (UTC); because getTime() gives the milliseconds elapsed since that moment, 0 is printed. java.sql.Date is used with its full name; its valueOf method produces a date from a text in the form yyyy-mm-dd and it is printed in the same form.

4.2.9Sample problems

The problems in this section are the sample problems and exercises of the slides. The answer to each has been verified by running it with JDK 21.

Example 4.2.1

The DigitalClock class written with access methods is used (hour 0–23, minute and second 0–59). What do the two code fragments below print? How many DigitalClock objects are created in the second fragment?

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());
00:30:59
45 10

In the first fragment setHour(25) and setSecond(-1) are rejected by the setters. The hour stays at its initial value 0; the minute is 30, and the second becomes 59 with the last valid call. The result is 00:30:59.

In the second fragment the assignment b = a creates no new object; both variables point to the same object. a.setMinute(15) and b.setMinute(45) are applied to the same object and the minute becomes 45. Then b is attached to a new object and its minute is made 10. a keeps pointing to the first object. The output is 45 10. In total two objects have been created, because new ran twice.

Example 4.2.2

Which of the lines A–E below give a compile error? Why?

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
    }
}
Test.java:5: error: second has private access in DigitalClock
        int x = s.second;                   // B
                 ^
Test.java:7: error: unexpected type
        s.getSecond() = 10;                 // D
                   ^
  required: variable
  found:    value
Test.java:8: error: incompatible types: String cannot be converted to int
        s.setSecond("40");                  // E
                    ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors

Line B tries to read a private field; the right way is s.getSecond(). In line D an assignment to the result of a method call is attempted. A method call is a value, not a variable; the required: variable, found: value in the message says this. The right way is s.setSecond(10). In line E "40" is a String and is not automatically converted to an int parameter. A and C are correct, because they call public methods.

Example 4.2.3

What does the following code print with the BankAccount class? Which balances are seen on the last line?

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());
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

The balance is 1000.0. The first withdrawal is rejected because 5000.0 exceeds the balance. −50.0 is an invalid deposit amount. Because the account is a checking account, no interest is added. The withdrawal of 250.0 is valid and the balance drops to 750.0. The second account is a savings account with a balance of 100.0. The transfer of 1000.0 is rejected because it exceeds the balance. The transfer of 750.0 is exactly the whole balance and satisfies the condition amount ≤ balance. First the target account's message (850.0), then the transfer's message (0.0) is printed. The last line is 0.0 850.0.

Example 4.2.4

(a) What does the first code below print with the non-copying ReportCard? What does it print with the defensively copying ReportCard? (b) What does the second code print with the Money class? (c) What happens if the Counter program that calls increment() ten times is run without -ea and with -ea? (d) Does new Ratio(1, 2).num compile in a class other than Ratio?

int[] d = {50, 60};
ReportCard k = new ReportCard(d);
int[] g = k.getGrades();
g[0] = 100;
d[1] = 100;
System.out.println(k.average());
Money p = new Money(100, "TL");
p.plus(p);
p = p.plus(p);
p.plus(new Money(1, "TL"));
System.out.println(p);

(a) In the non-copying version d, g and the field point to the same array. Both assignments reach the object: the array becomes {100, 100} and the average is 100.0. In the version with defensive copies both assignments go to copies; the object's array stays {50, 60} and the average is 55.0. JDK 21 gives these values in both versions.

(b) The results of the calls p.plus(p) and p.plus(new Money(1, "TL")) are discarded. Only p = p.plus(p) is kept: 100 + 100 = 200 kuruş. The output is 2.00 TL. That an object takes itself as an argument is also no problem, because plus changes no object.

(c) Without -ea the assert line does not run and the program prints done; the error is not visible. With -ea, on the tenth increment the value becomes 10 and AssertionError: value=10 is thrown. Only the second run shows the error.

(d) No. The compiler gives the error num has private access in Ratio. private access is free only in the code of Ratio itself.

Example 4.2.5

Let us write four small classes. Student: private name and grade; the grade is accepted only between 0 and 100; passed() returns true if the grade is ≥ 50. Point: accepts only non-negative coordinates; distance() returns the distance from the origin. Thermometer: stores a Celsius value and rejects anything below −273.15; getFahrenheit() computes without a separate field. Counter: has only the methods increment(), reset() and getValue().

public class Student {
  private String name;
  private int grade;
  public Student(String name) { this.name = name; }
  public void setGrade(int grade) {
    if (grade >= 0 && grade <= 100) this.grade = grade;
  }
  public int getGrade() { return grade; }
  public boolean passed() { return grade >= 50; }
}
public class Point {
  private double x, y;
  public Point(double x, double y) { setX(x); setY(y); }
  public void setX(double x) { if (x >= 0) this.x = x; }
  public void setY(double y) { if (y >= 0) this.y = y; }
  public double getX() { return x; }
  public double distance() { return Math.sqrt(x * x + y * y); }
}
public class Thermometer {
  private double celsius;
  public Thermometer(double c) { setCelsius(c); }
  public void setCelsius(double c) { if (c >= -273.15) celsius = c; }
  public double getCelsius() { return celsius; }
  public double getFahrenheit() { return celsius * 9 / 5 + 32; }
}
public class Counter {
  private int value;
  public void increment() { value++; }
  public void reset() { value = 0; }
  public int getValue() { return value; }
}
public class Exercise {
  public static void main(String[] args) {
    Student o = new Student("Ece");
    o.setGrade(120);
    System.out.println(o.getGrade() + " " + o.passed());
    o.setGrade(75);
    System.out.println(o.getGrade() + " " + o.passed());
    Point n = new Point(3, 4);
    System.out.println(n.distance());
    n.setX(-7);
    System.out.println(n.getX());
    Thermometer t = new Thermometer(25);
    System.out.println(t.getFahrenheit());
    t.setCelsius(-300);
    System.out.println(t.getCelsius());
    Counter s = new Counter();
    s.increment(); s.increment(); s.increment();
    System.out.print(s.getValue() + " ");
    s.reset();
    System.out.println(s.getValue());
  }
}
0 false
75 true
5.0
3.0
77.0
25.0
3 0

setGrade(120) is rejected and the grade stays at 0: 0 false. After setGrade(75), 75 true is printed. The constructor of Point calls the setters; the rule thus stays in one place. For new Point(3, 4) the distance is √(9 + 16) = 5.0. setX(-7) is rejected and x stays 3.0. 25 °C is 25 × 9 / 5 + 32 = 77.0 °F. The derived value is not kept in a separate field; had it been, the two fields would have to be kept consistent on every change. After setCelsius(-300) the value stays 25.0.

Counter has no setter, because the value of the counter should only increase one by one or be reset. A setValue would break this rule. Three increment() calls make the value 3; reset() returns it to 0.

A small note on the constructor calling setters: when compiled with javac -Xlint:all, JDK 21 gives the warning possible 'this' escape for Point and Thermometer. The warning says that a subclass could override these methods and see a half-built object. If the class is made final, or the methods called are final or private, the warning disappears.

Example 4.2.6

(a) The Student class is to be moved to the school package and used from app.Main. Which lines are added, and what are the compile and run commands? (b) An opCount field with only a getter is to be added to BankAccount; it increases by one on every successful deposit and withdrawal. At the end of the two-account trace example, what is the operation count of the two accounts?

(a) package school; is written at the top of Student.java, and package app; and import school.Student; at the top of Main.java. The files are put in the folders src/school/ and src/app/. The commands: javac -d out src/school/Student.java src/app/Main.java and java -cp out app.Main. The Student class and the methods used must be public.

1 2

(b) The counter is incremented in deposit and withdraw, only on the successful branches. The counter of acc1 is 1: only deposit(500.0) counts. addInterest is not a deposit; transfer deducts directly from its own balance and does not call its own withdraw. The counter of acc2 is 2: withdraw(200.0) and the deposit inside the transfer. This result also shows a side effect of the transfer not doing its own side of the operation through withdraw. If the rules are to be gathered in one place, transfer should call withdraw too.

4.2.10Common mistakes

The compiler catches some of the mistakes related to encapsulation and points to their location with its message. The others lead to programs that compile but silently corrupt the object. Those in the second group are more dangerous.

Common mistake

Accessing a private field from outside. Message: second has private access in DigitalClock. Instead of s.second = 75;, write s.setSecond(75);; to read, use s.getSecond().

Common mistake

Forgetting this in a setter. width = width; compiles but assigns the parameter to itself; the field does not change and getWidth() returns 0. The correct form is this.width = width;.

Common mistake

Writing a getter as void. The line public void getWidth() { return width; } gives the error incompatible types: unexpected return value. A void method cannot return a value; the return type must be the type of the field, that is, int.

Common mistake

Writing a setter without validation. public void setSecond(int s) { second = s; } is no different from making the field public. The validity rule is checked in the setter.

Common mistake

Writing a method name without parentheses. In the line int d = s.getMinute; the compiler looks for a field called getMinute: cannot find symbol ... variable getMinute. A method call is always written with parentheses.

Common mistake

Not writing an interface method. Message: SportsCar is not abstract and does not override abstract method stop() in Car. A class that says implements must write all the methods in the interface.

Common mistake

Handing out the inner object through a getter. return grades; exposes a mutable array or list to the outside. A copy or a read-only view is returned. The array that comes into the constructor is copied too.

Common mistake

Thinking a final field is immutable. When private final int[] grades is written, what is fixed is the reference, not the elements of the array. grades[0] = 0; compiles.

Common mistake

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

Common mistake

Forgetting import, or thinking a subpackage is imported. Message: cannot find symbol ... class Scanner. After import java.util.*; the same error appears for Function; java.util.function is imported separately.

Common mistake

Using a package-private class from outside. Message: Helper is not public in bank; cannot be accessed from outside package. The class is either made public or used only from the same package. The methods used must be public too.

Common mistake

Writing a setter for every field. The rule slides over to the code that uses the class. Behavior (withdraw, addBonus) is designed first; most of the time no setter is needed.

Common mistake

Swallowing the error silently. Ignoring an invalid value without leaving any trace hides the error. The behavior is either stated explicitly in the contract or an exception is thrown.

4.2.11Summary

  • Encapsulation is gathering the data and the methods that process it in a class and closing the data off from the outside. In Java, fields are written private and behaviors public.
  • Information hiding separates the "what" of a task from its "how". The user knows only the method signature and its contract; the user does not know the steps behind the call service.addData("Ayşe").
  • A precondition is the state assumed true before the call, a postcondition the state guaranteed after the call. Together they are the method's contract and are written in Javadoc with the tags @param, @return and @throws. The < signs in a comment are put inside {@code ...}.
  • When the precondition is broken, the method may ignore the value, return a status or throw an exception. For public methods the customary choice is IllegalArgumentException.
  • A class invariant is a rule every object satisfies at every moment. assert checks the invariant during development, but works only with -ea; it is not used for argument checking.
  • There are four access levels: public (everywhere), protected (package and subclasses), package access (package only) and private (class only). The most restrictive level is preferred. private access is checked per class, not per object.
  • A getter returns the field, a setter checks the new value and assigns it. Because the parameter shadows the field, the assignment is written as this.field = field;.
  • The constructor must validate too. If a constructor throws an exception, new produces no reference and the invalid object never reaches the user.
  • The interface is the outer face of a class and the implementation its internal mechanism. interface and implements turn this distinction into a construct the compiler checks. Even when the implementation changes, the interface can stay the same: the two-field and the single-field clock give the same output.
  • "Tell, don't ask": the object that holds the data makes the decision; a setter is written only if the field can really change freely.
  • The reference to a mutable inner object can leak. A defensive copy is made in the constructor and the getter, or a read-only view is given. final fixes only the reference.
  • An immutable class has no setters, its fields are private final, the class is final, and "changing" methods return a new object. Forgetting to assign the result (a.plus(p);) is the most frequent mistake.
  • A package is a group of classes in a folder; the full name of a class includes its package. A packaged program is compiled with javac -d out ... and run with java -cp out pkg.Class. import lets a class from another package be used by its short name; it does not bring in subpackages. Of two classes with the same name, one is imported and the other is written with its full name.

4.2.12Key terms

  • encapsulation
  • information hiding
  • data hiding
  • abstraction
  • precondition / postcondition
  • class invariant
  • assertion
  • exception
  • access modifier
  • accessor (getter)
  • mutator (setter)
  • shadowing
  • this keyword
  • constructor
  • field
  • reference
  • interface
  • interface vs. implementation
  • implement
  • defensive copy
  • immutable
  • record
  • package
  • import

4.2.13Test Yourself

  1. For DigitalClock written with access methods, this code is run: DigitalClock a = new DigitalClock(); DigitalClock b = a; a.setHour(23); b.setHour(a.getHour() + 1); a.setMinute(a.getMinute() - 1); b.setSecond(59); a.show();. What is printed?

    Answer

    a and b point to the same object. The hour becomes 23. b.setHour(24) is rejected, because valid hours are 0–23. setMinute(-1) is rejected too and the minute stays at 0. The second becomes 59. Output: 23:00:59.

  2. The public class A in package p1 has the fields public int pub, protected int prot, int pkg with no modifier and private int priv. In package p2, a method of the class C extends p1.A assigns a value to all four fields by their own names. Which assignments do not compile?

    Answer

    The assignments to pub and prot compile: public is accessible from everywhere and protected from a subclass in another package. For pkg the error pkg is not public in A; cannot be accessed from outside package appears, and for priv the error priv has private access in A.

  3. A single-field (totalSeconds) DigitalClock has just been created. setMinute(59), setSecond(59) and setMinute(0) are called in turn. What is totalSeconds after each call? What does getMinute() + ":" + getSecond() give at the end?

    Answer

    In the first call the difference is 59 minutes: 59 · 60 = 3540. In the second getSecond() is 0 and 59 is added: 3599. In the third getMinute() is 3599 / 60 % 60 = 59; the difference is −59 minutes, that is, −3540 seconds: 59. The result is 0:59. The second part is not affected by the change of minute.

  4. The condition in the addData method has been written by mistake as if (data.isEmpty() || data == null). What happens on the call addData(null)? If the condition is made data == null || data.trim().isEmpty(), how many of the arguments " ", null and " a b " add a record?

    Answer

    In the first form isEmpty() is called on null and the program stops with a NullPointerException; the short circuit of || helps only if the left side is true. In the second form " " is empty after trimming and is rejected, null is rejected in the first condition; only " a b " is added. JDK 21 output: false false true 1.

  5. In a Javadoc comment, @param n must satisfy 0 < n < 10 has been written. What does the javadoc command do? How is the comment fixed?

    Answer

    Javadoc processes the comment as HTML and takes a raw < sign to be the start of a tag. JDK 21 gives a malformed HTML error. The fix: @param n must satisfy {@code 0 < n < 10}. The text inside {@code ...} is shown as it is. Writing &lt; also works, but it is hard to read in the source.

  6. From the list List<Integer> inner = new ArrayList<>(List.of(70, 80));, view = Collections.unmodifiableList(inner) and copy = new ArrayList<>(inner) are produced; then inner.add(90) runs. What do view and copy contain? What does view.add(100) do?

    Answer

    The view does not copy; it shows the inner list: [70, 80, 90]. The copy is independent: [70, 80]. view.add(100) throws an UnsupportedOperationException. The view prevents changes from outside but reflects the changes made inside the class itself.

  7. With the Money class, what does System.out.println(new Money(-50, "TL")); print? Is this a bug; what rule can be added to the class?

    Answer

    Because −50 / 100 = 0 and −50 % 100 = −50, 0.-50 TL is printed. The amount looks meaningless. If the class will not allow negative amounts, the constructor should throw an IllegalArgumentException for cents < 0. If it will allow them, toString should write the sign separately and work with the absolute value.

  8. javac -d out src/bank/Account.java src/app/Main.java was run in the project folder. Then java -cp out/app Main was tried. What happens, and why?

    Answer

    Java finds the file out/app/Main.class, but the full name of the class in the file is app.Main. Result: NoClassDefFoundError: Main (wrong name: app/Main). The right command is java -cp out app.Main: the classpath is the root of the packages and the class name is the full name.

  9. The constructor of the Product class assigns the price with setPrice; setPrice silently ignores a non-positive value. What does new Product("Pen", -5).getPrice() return? What is the problem with this design?

    Answer

    No assignment is made and the field stays at its default value 0.0. The object has been built, but a product with price 0 breaks the invariant "positive price only". Silent rejection does not work in a constructor. The constructor should throw an IllegalArgumentException for an invalid value, so that the object is never built.

4.2.14Further reading

  • J. Bloch, Effective Java (3rd ed., Addison-Wesley, 2018), Items 15–17. Explains, in short rules with reasons, minimizing the accessibility of classes and members, minimizing mutability, and using accessor methods instead of public fields.
  • Oracle, The Java Tutorials, "Controlling Access to Members of a Class" and "Creating and Using Packages": explain the access levels and the compilation of packaged programs with official examples.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), Chapter 11 "Designing Classes": builds a class step by step with its fields, constructors, access methods and invariants; it can be read free online.
  • J. Gosling et al., The Java Language Specification, Java SE 21, §6.6 and §7: the precise rules of access control and packages; the reference to consult especially for the details of protected access.

4.2.15References

  • 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: minimizing accessibility, accessor methods instead of public fields).
  • A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 11: Designing Classes).