Chapter 4.2: Encapsulation

Chapter 4.2: Encapsulation · Study Questions
Information hidingPreconditions and postconditionsAccess modifiersGetters and settersBank accountChanging the implementationPackages and importClass name clashes
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Encapsulation and Information Hiding

Question 1: The Essence of Encapsulation

Which statement describes encapsulation best?

B: Encapsulation gathers the fields (usually private) and the methods that work on them in one unit; from outside, only the methods the class offers are used. A describes inheritance and C describes overloading; D does not protect the data, it exposes it to everyone.

Multiple Choice · Encapsulation and Information Hiding

Question 2: What Is Safe to Change?

Other classes use the class DigitalClock only through public methods such as getMinute() and setMinute(int). Which change does not break the code that uses them?

D: Hidden fields are part of the implementation; as long as the signatures of the methods stay the same, the code that uses them does not change. A, B and C change the class's interface (its outside face): every line that calls those methods gives a compile error.

Multiple Choice · Preconditions and Postconditions

Question 3: Responsibility in a Contract

The comment of the method double squareRoot(double x) says "Precondition: x ≥ 0. Postcondition: the square of the result equals x." Which statement is true?

A: The precondition is the state assumed to hold before the call, and ensuring it is the caller's responsibility; once it holds, guaranteeing the postcondition is the method's responsibility. If the precondition is broken, the method guarantees nothing (C); D is the definition of a precondition.

Output Question · Preconditions and Postconditions

Question 4: A Registry Contract

The precondition of the method add: "data is not null and not empty". What does the program print?

class Registry {
  private int count = 0;
  public boolean add(String data) {
    if (data == null || data.isEmpty()) {
      return false;
    }
    count++;
    return true;
  }
  public int getCount() { return count; }
}
// in main:
Registry r = new Registry();
System.out.println(r.add("Ali") + " " + r.add("")
    + " " + r.add(" ") + " " + r.add(null));
System.out.println(r.getCount());
Show answer
true false true false
2
  • "" is empty (isEmpty() → true), so it is rejected.
  • " " contains a space character: its length is 1, isEmpty() → false; it passes the check and is counted.
  • For null the first condition is true, so || does not look at the second; no NullPointerException occurs.
  • Two successful additions: getCount() → 2. To reject blanks as well, data.trim().isEmpty() can be used.

Output Question · Preconditions and Postconditions

Question 5: assert On and Off

The program is run first with java Root, then with java -ea Root. What is seen in the two runs?

public class Root {
  static int root(int x) {
    assert x >= 0 : "negative: " + x;
    return (int) Math.sqrt(x);
  }
  public static void main(String[] args) {
    System.out.println(root(16));
    System.out.println(root(-4));
  }
}
Show answer

java Root:

4
0

Assertions are off by default; the assert line never runs. Math.sqrt(-4) is NaN, and (int) turns NaN into 0: the error passes silently.

java -ea Root:

4
Exception in thread "main"
java.lang.AssertionError: negative: -4

The condition is false: AssertionError with the message. assert is for "this must not happen" assumptions during development; user input is checked with an exception (IllegalArgumentException), because assertions may be off in production.

Multiple Choice · Access Modifiers

Question 6: Package Access

Who can directly access a field int counter; declared in a class without an access modifier?

C: If no modifier is written, package access (package-private) applies: the class itself and the classes in the same package can access it. A is the private level and B the public level; a subclass in another package cannot see a package-private member.

Multiple Choice · Access Modifiers

Question 7: Access Levels

Which statement is true about access modifiers?

C: A top-level class cannot be private or protected. private is open only to the class itself (A); if no modifier is written, package access applies (B); a protected member is limited to the same package and subclasses (D).

Spot the Bug · Access Modifiers

Question 8: Which Lines Do Not Compile?

The class Clock has private int minute;, public int getMinute() and a public void setMinute(int) that rejects values outside 0–59. Which of the lines A–E in another class give a compile error? If the faulty lines are deleted, what is s.getMinute()?

Clock s = new Clock();
s.setMinute(30);                 // A
s.minute = 15;                   // B
int d = s.getMinute;             // C
s.setMinute(s.getMinute() + 5);  // D
String t = s.getMinute();        // E
Show answer
  • B: minute has private access in Clock.
  • C: no parentheses; the compiler looks for a field named getMinute: cannot find symbol … variable getMinute.
  • E: incompatible types: int cannot be converted to String.
  • A and D are correct. If only A and D remain, the minute goes 30 → 35: 35.

Step-by-Step Trace · Getters and Setters

Question 9: Setter Protection

Which of the three setGrade calls change the field? What does the program print?

StackHeapmain()o#1 Studentgrade0

The object is created; the private field grade starts with the default value 0.

StackHeapsetGrade(int grade)thisgrade-5main()o#1 Studentgrade0

The parameter grade shadows the field; in the condition, grade is the parameter: −5 ≥ 0 is false.

StackHeapmain()o#1 Studentgrade0

The assignment line is skipped; an invalid value cannot get into the object. The field stays 0.

StackHeapsetGrade(int grade)thisgrade40main()o#1 Studentgrade40

40 is in range: this.grade = grade fills the field on the left with the parameter on the right.

StackHeapsetGrade(int grade)thisgrade130main()o#1 Studentgrade40

130 > 100: the condition is false, the field stays at 40.

StackHeapgetGrade()thismain()o#1 Studentgrade40

getGrade() returns the value of the field: 40.

StackHeapmain()o#1 Studentgrade40

hasPassed(): 40 ≥ 50 is false. The output: 40 false.

class Student {
  private int grade;
  public void setGrade(int grade) {
    if (grade >= 0 && grade <= 100) {
      this.grade = grade;
    }
  }
  public int getGrade() { return grade; }
  public boolean hasPassed() { return grade >= 50; }
}
// in main:
Student o = new Student();
o.setGrade(-5);
o.setGrade(40);
o.setGrade(130);
System.out.println(o.getGrade() + " " + o.hasPassed());

Multiple Choice · Getters and Setters

Question 10: When this Is Forgotten

What does Box b = new Box(); b.setWidth(5); System.out.println(b.getWidth()); print?

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

B: In the method, the name width refers to the parameter; the parameter shadows the field. width = width; assigns the parameter to itself, and the field stays at its default 0. The compiler gives no error (C is wrong); the correct form is this.width = width;.

Step-by-Step Trace · Example: Bank Account

Question 11: A Transfer Between Two Accounts

Which calls change the balance and which are rejected? What does the program print?

StackHeapmain()a1a2#1 Accountbalance300.0#2 Accountbalance50.0

Two independent objects; each has its own balance field.

StackHeaptransferthistargetm120.0main()a1a2#1 Accountbalance300.0#2 Accountbalance50.0

a1.transfer(a2, 120.0): this = #1, target = #2.

StackHeapwithdrawthism120.0transferthistargetm120.0main()a1a2#1 Accountbalance180.0#2 Accountbalance50.0

withdraw(m) is called on the same object (this.withdraw): 120 ≤ 300, the balance is 180.0; true is returned.

StackHeapdepositthism120.0transferthistargetm120.0main()a1a2#1 Accountbalance180.0#2 Accountbalance170.0

target.deposit(m): this time this = #2. The balance is 50 + 120 = 170.0.

StackHeapwithdrawthism400.0transferthistargetm400.0main()a1a2#1 Accountbalance180.0#2 Accountbalance170.0

a2.transfer(a1, 400.0): 400 > 170, withdraw returns false; deposit is never called.

StackHeapwithdrawthism-20.0main()a1a2#1 Accountbalance180.0#2 Accountbalance170.0

a2.withdraw(-20.0): the precondition (m > 0) is broken, false. A negative withdrawal cannot increase the balance.

StackHeapmain()a1a2#1 Accountbalance180.0#2 Accountbalance170.0

The output: 180.0 170.0. The total money is preserved: 300 + 50 = 180 + 170.

class Account {
  private double balance;
  Account(double b) { balance = b; }
  double getBalance() { return balance; }
  void deposit(double m) { if (m > 0) balance += m; }
  boolean withdraw(double m) {
    if (m <= 0 || m > balance) return false;
    balance -= m;
    return true;
  }
  void transfer(Account target, double m) {
    if (withdraw(m)) target.deposit(m);
  }
}
// in main:
Account a1 = new Account(300.0);
Account a2 = new Account(50.0);
a1.transfer(a2, 120.0);
a2.transfer(a1, 400.0);
a2.withdraw(-20.0);
System.out.println(a1.getBalance() + " " + a2.getBalance());

Coding Question · Example: Bank Account

Question 12: A Product with a Discount

Write the class Product: private name and price; a constructor; getPrice(); setPrice(double), which accepts only a positive price; and applyDiscount(int percent), whose precondition is 0 < percent ≤ 50 and which returns true if the discount was applied. For new Product("Notebook", 80.0), what is the price after applyDiscount(25), applyDiscount(70) and setPrice(-10)?

Show answer
class Product {
  private String name;
  private double price;
  public Product(String name, double price) {
    this.name = name;
    setPrice(price);
  }
  public double getPrice() { return price; }
  public void setPrice(double price) {
    if (price > 0) this.price = price;
  }
  public boolean applyDiscount(int percent) {
    if (percent <= 0 || percent > 50) return false;
    price = price * (100 - percent) / 100;
    return true;
  }
}

true 60.0, then false 60.0 (70 is rejected), and after setPrice(-10) it is still 60.0. Because the constructor also calls setPrice, the rule stays in one place.

Step-by-Step Trace · Class Design

Question 13: A Clock with a Single Field

The clock keeps minutes and seconds in a single field. What is totalSeconds after each call? What does the program print?

StackHeapmain()s#1 DigitalClocktotalSeconds0

The time is kept in one field instead of two: the seconds elapsed since midnight.

StackHeapsetMinute(5)thisdiff5main()s#1 DigitalClocktotalSeconds300

getMinute() returns 0; diff = 5 − 0 = 5 minutes → +300 seconds.

StackHeapsetSecond(30)thissecond30main()s#1 DigitalClocktotalSeconds330

getSecond() = 300 % 60 = 0; 30 − 0 is added: 330.

StackHeapgetMinute()thissetMinute(2)thisdiff?main()s#1 DigitalClocktotalSeconds330

getMinute(): 330 / 60 = 5, 5 % 60 = 5.

StackHeapsetMinute(2)thisdiff-3main()s#1 DigitalClocktotalSeconds150

diff = 2 − 5 = −3 → totalSeconds 330 − 180 = 150. The seconds part (30) is preserved.

StackHeapsetSecond(75)thissecond75main()s#1 DigitalClocktotalSeconds150

75 is out of range: the condition is false, the field does not change.

StackHeapmain()s#1 DigitalClocktotalSeconds150

150 / 60 % 60 = 2 and 150 % 60 = 30. The output: 2:30. The code that uses the class never knows the internal structure changed.

class DigitalClock {
  private int totalSeconds = 0;
  int getMinute() { return totalSeconds / 60 % 60; }
  int getSecond() { return totalSeconds % 60; }
  void setMinute(int minute) {
    if (minute < 0 || minute > 59) return;
    int diff = minute - getMinute();
    totalSeconds += diff * 60;
  }
  void setSecond(int second) {
    if (second >= 0 && second < 60)
      totalSeconds += second - getSecond();
  }
}
// in main:
DigitalClock s = new DigitalClock();
s.setMinute(5); s.setSecond(30);
s.setMinute(2); s.setSecond(75);
System.out.println(s.getMinute() + ":" + s.getSecond());

Multiple Choice · Class Design

Question 14: Implementing an Interface

Does this code compile?

interface Car {
  void move();
  void stop();
}
class SportsCar implements Car {
  public void move() {
    System.out.println("moving");
  }
}

A: The compiler says SportsCar is not abstract and does not override abstract method stop() in Car. A class that says implements Car must implement every abstract method of the interface (or be abstract itself). There is no need to write public in an interface; the methods are implicitly public abstract (D is wrong).

Multiple Choice · Packages

Question 15: Running a Program with Packages

The file src/app/Main.java starts with package app; and contains main. It was compiled in the project folder with javac -d out src/bank/Account.java src/app/Main.java. Which command runs the program?

D: -d out writes the classes under out/ with their package folders; to run, the class path out is given and the full name of the class (package + class, with a dot) is written. B lacks the package name; A and C give a file path, not a class name.

Spot the Bug · Packages

Question 16: Access from Outside the Package

The two files are compiled together. Which errors appear? What are the minimum changes needed for the program to print Ece?

// src/school/Student.java
package school;
class Student {
  private String name;
  public Student(String name) { this.name = name; }
  String getName() { return name; }
}
// src/app/Main.java
package app;
import school.Student;
public class Main {
  public static void main(String[] args) {
    Student o = new Student("Ece");
    System.out.println(o.getName());
  }
}
Show answer
error: Student is not public in school;
  cannot be accessed from outside package

A class without a modifier is package-private; it cannot be seen from the package app (the same error on the import line and everywhere it is used).

When the class is made public, the second error appears: getName() is not public in Student; cannot be accessed from outside package. The method is package-private too.

What is needed: public class Student and public String getName(). The constructor is already public.

Multiple Choice · Packages

Question 17: A Class That Needs No import

A class has no import line and uses no full names. Which of the following can be used by its short name?

C: The java.lang package (String, Math, System, Integer…) is visible to every file automatically. Scanner, ArrayList and Random are in java.util; an import or the full name (java.util.Random) is needed.

Spot the Bug · Packages

Question 18: Two Dates

Does the program compile? If not, what is the error? How can it be fixed so that java.util.Date is used by its short name and java.sql.Date can also be used?

import java.util.*;
import java.sql.*;
public class Dates {
  public static void main(String[] args) {
    List<String> l = new ArrayList<>();
    Date date = null;
  }
}
Show answer
error: reference to Date is
  ambiguous: both class
  java.sql.Date in java.sql and
  class java.util.Date in
  java.util match

The two * imports bring in two classes with the same name; List and ArrayList are not a problem, only Date is ambiguous.

The fix: add import java.util.Date; (a single-class import takes precedence over *); write the other one with its full name: java.sql.Date record = java.sql.Date.valueOf("2025-03-01");

The End

Chapter 4.2: Encapsulation: Study Questions
Lecture slides: Chapter 4.2: Encapsulation · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.