Encapsulation and access control
-
Fine-grained control on attributes and methods.
-
Support encapsulation / Information hiding.
Purpose: Hide implementation details within class or package
|
|
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
private
unless you have a good reason not to. -
Avoid
public
fields except for constants. Public fields tend linking to a particular implementation and limit your flexibility in changing your code.
No. 86
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. 87
Explaining times
Q: |
In Figure 212, “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. |