Encapsulation and access control
-
Fine-grained control on attributes and methods.
-
Support encapsulation / Information hiding.
Purpose: Hide implementation details within class or package
public class DayTime {
private int ❶ minutes_since_0_00;
public int getMinute() { ❷
return minutes_since_0_00 % 60;
}
public int getHour() {❷
return minutes_since_0_00 / 60;
}
} |
public class DayTime {
private int minute, hour;❶
public int getMinute() { ❷
return minute;
}
public int getHour() { ❷
return hour;
}
} |
No access to private field of alien
class Time:
public class Q {
public static void main(String[] args) {
Time t = new Time();
// Error: 'minutes_since_0_00' has private access in 'Time'
t.minutes_since_0_00 = 371;
}
}| Access Level | Other package | Child class | Same package | Same class |
public |
yes | yes | yes | yes |
protected |
no | yes | yes | yes |
| Default | no | no | yes | yes |
private |
no | no | no | yes |
-
Use the most restrictive access level that makes sense for a particular member.
-
Use
privateunless you have a good reason not to. -
Avoid
publicfields except for constants. Public fields tend linking to a particular implementation and limit your flexibility in changing your code.
No. 89
Understanding access control
|
Q: |
Follow the example given in “Classes and Packages
of the Example Used to Illustrate Access Levels” and
define two respective classes |
||||||||
|
A: |
NoteNotice the related follow up inheritance exercise. |
No. 90
Explaining times
|
Q: |
In Figure 217, “Example: Two ways implementing a day's time ” we have: Explain the term |
|
A: |
Every 60 minutes a new hour begins and minutes start from zero again. The term Example: If there are 134 minutes elapsed since midnight this amounts to 134 / 60 == 2 hours and 134 % 60 == 14 minutes. |
