Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Encapsulation mistakes come in two kinds. Some stop javac, and the message names the line; the fix is almost never to make something public. The dangerous ones compile and run, and quietly let a wrong value into an object.

Mistakes and fixes at a glance

The most common compile error in this module is has private access: code in another class used a private field, method or constructor. The fix is to call the public method the class offers, not to make the member public.

Example 1 · has private access: a field written from main

AccessDemo.javaJava
class Student {    private int marks;
    public void setMarks(int marks) {        if (marks >= 0 && marks <= 100) {            this.marks = marks;        }    }
    public int getMarks() {        return marks;    }}
public class AccessDemo {    public static void main(String[] args) {        Student s = new Student();        s.marks = 95;        System.out.println(s.getMarks());    }}
Sample compiler output
AccessDemo.java:18: error: marks has private access in Student
        s.marks = 95;
         ^
1 error

What this code does

  • marks is private, so only code inside Student may use it. AccessDemo is another class, so javac stops at line 18.
  • Fix: s.setMarks(95);. The program then prints 95, and a bad value such as 150 would be refused by the check.

Review: private fields and public methods (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:

Mistakes that compile but are wrong

These bugs give no error: the program runs and prints a wrong answer. The most common one is a field that lost its private, so main writes it directly and skips the checking setter.

Example 2 · Forgot private: the setter is skipped

MissingPrivateDemo.javaJava
class Student {    int marks;   // private is missing
    public void setMarks(int marks) {        if (marks < 0 || marks > 100) {            throw new IllegalArgumentException("Marks must be 0 to 100");        }        this.marks = marks;    }
    public int getMarks() {        return marks;    }}
public class MissingPrivateDemo {    public static void main(String[] args) {        Student s = new Student();        s.setMarks(75);        s.marks = 500;        System.out.println("Marks: " + s.getMarks());    }}
Output
Marks: 500

What this code does

  • The setter is perfect, but the field has default access, so main writes it directly and the check never runs.
  • With private int marks;, the line s.marks = 500; would be a compile error instead of a hidden bug.

A getter must only read

Reading a balance three times should not change it. A side effect is a change a method makes besides returning its answer; a getter with one surprises every caller.

Example 3 · A getter with a side effect

SideEffectDemo.javaJava
class Account {    private int balance = 1000;
    public int getBalance() {        balance = balance - 2;   // SMS fee, in the wrong place        return balance;    }}
public class SideEffectDemo {    public static void main(String[] args) {        Account a = new Account();        System.out.println("Balance: Rs. " + a.getBalance());        System.out.println("Balance: Rs. " + a.getBalance());        System.out.println("Balance: Rs. " + a.getBalance());    }}
Output
Balance: Rs. 998
Balance: Rs. 996
Balance: Rs. 994

What this code does

  • Just reading the balance three times changed it three times. Nobody expects a getter to change anything.
  • Charges belong in action methods like withdraw or sendAlert. A getter should only return a value.

Other design slips have no wrong line at all: a setter for every field by habit, setBalance instead of deposit and withdraw, helpers left public, and setters that print and carry on instead of throwing. Review: Design methods, not just setters (opens in a new tab)

Spot the bug

Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask three questions: can this code reach the member, does the value reach the field, and can anyone change it without a check?

Find the bug

Find the encapsulation bug

Select the line that is wrong.

main should give Rohan 5 bonus marks.

Round 1 of 5

When in doubt, trace the arrays

A class copies in its getter, yet a change in main still reaches it. Trace it: for every variable and field, write which array it leads to, then update the arrays line by line.

Trace the code

Trace one copy and one leak

import java.util.Arrays;
class Card {
private int[] marks;
public Card(int[] marks) {
this.marks = marks;
}
public int[] getMarks() {
return Arrays.copyOf(marks, marks.length);
}
}
public class CardTrace {
public static void main(String[] args) {
int[] m = {40, 50};
Card c = new Card(m);
int[] copy = c.getMarks();
copy[0] = 99;
m[1] = 0;
System.out.println(Arrays.toString(c.getMarks()));
}
}

Variables

m
array A [40, 50]

Output

(nothing printed yet)

Line 17m refers to a new array. Call it array A.

Step 1 of 6

Finish up

Mark complete & continue

Next: Must-do problems: Encapsulation