|
|
Declarations and Access Control - Access Control
- accessibility is a static that can be determined at compile time
- it depends only on types and declaration modifiers
- accessibility effects inheritance of class members including hiding and overriding
Determining accessibility (JLS §6.6.1)
- a package is always accessible
- a public class or interface is accessible from any code as long as it's compilation unit is reachable by the code
- an array is accessible if and only if it's element type is accessible
- a member of a reference type (ie a class, interface, field or method of an object reference) or a class constructor is accessible only if the member was declared to allow access
- declared public, all code can access the member
- declared protected, accessible from other code within the same package or from subclasses in other packages if the outside code is involved in the implementation of the class. For example, the following produces a compile-error
package point;
class Point {
protected int x, y;
}
package threepoint;
import point.Point;
class ThreePoints extends Point {
protected int z;
public void delta(Point p) {
p.x += this.x; // compile-error: cannot access p.x
p.y += this.y; // compile-error: cannot access p.y
}
}
Even though ThreePoints is a subclass of Point, it cannot
access the protected fields in Point. The subclass must be
involved in the implementation of Point. The fact that the
code is within the body of a subclass is irrelevant. To the
compiler, Point is a type reference and p.x and p.y are
declared protected in the type Point.
If the parameter is changed to ThreePoints p the code will
compile as the type ThreePoints inherits the protected fields
x and y from Point.
- declared private, accessible only from within the body of the enclosing class; private members are not inherited
class Private1 {
private boolean state;
Private1() {
System.out.println("Private1 state: " + state);
}
}
class Private2 extends Private1 {
Private2() {
// compile-error
System.out.println("Private1 state: " + state);
}
}
- if no access was declared, default access applies ie accesible only from code within the same package
Example Code
|