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
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()); }}AccessDemo.java:18: error: marks has private access in Student
s.marks = 95;
^
1 errorWhat this code does
marksis private, so only code insideStudentmay use it.AccessDemois another class, sojavacstops at line 18.- Fix:
s.setMarks(95);. The program then prints95, 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:
cannot find symbolforsetRollNo→ the class has no setter on purpose, because the value is fixed → read it with the getter. Review: Getters and setters (opens in a new tab)missing return statementin a getter → it prints the value instead of returning it →return price;. Review: Getters and setters (opens in a new tab)- The getter returns
nullafter the setter ran →city = city;copies the parameter into itself →this.city = city;. Review: Getters and setters (opens in a new tab) - A refused value is still saved → the check comes after the assignment, or the constructor writes the field directly → check first, and let the constructor call the setter. Review: Keep objects valid with checks (opens in a new tab)
- The object changes with no setter → a getter or the constructor shares a private array → copy in and copy out. Review: Read-only fields and computed values (opens in a new tab)
- A total is out of date → it is stored instead of computed → work it out in the getter. Review: Read-only fields and computed values (opens in a new tab)
- The balance goes negative → every caller uses
setBalanceand must remember the rule →depositandwithdrawthat check. Review: Design methods, not just setters (opens in a new tab)
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
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()); }}Marks: 500
What this code does
- The setter is perfect, but the field has default access, so
mainwrites it directly and the check never runs. - With
private int marks;, the lines.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
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()); }}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
withdraworsendAlert. 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 5When 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
Variables
- m
- array A [40, 50]
Output
(nothing printed yet)Line 17m refers to a new array. Call it array A.
Finish up
Mark complete & continue
Next: Must-do problems: Encapsulation