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 ❶ minutesSinceMidnight;
public int getMinute() { ❷
return minutesSinceMidnight % 60;
}
public int getHour() {❷
return minutesSinceMidnight / 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) {
DayTime t = new DayTime();
// Error: 'minutesSinceMidnight' has private access in 'Time'
t.minutesSinceMidnight = 371;
}
}No access modifier = package - local access
package a; public class X{ // No public // modifier int i; } |
package a; public class Y { void displayValues(X x) { // o.K. System.out.println(x.i); } } |
package b; // X resides in different package import a.X; public class Z { void displayValues(X x) { // Error: // 'i' is not public in 'a.X' // Cannot be accessed from // outside package System.out.println(x.i); } } |
| Access Level | Other package | Child class | Same package | Same class |
public |
yes | yes | yes | yes |
protected |
no | yes | yes | yes |
| [omitted] | 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. 91
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. 92
Explaining times
|
Q: |
In Figure 226, “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. |
