Access control modifiers let you specify what types (mainly classes) and members of those types are accessible from other types and members, in order to get a proper encapsulation. The following table summarizes the meaning of the four (really three) available access control modifiers in Java. You can read the content of it as “A member having the modifier X is accessible from…”:
Class | Package1 | Subclass 2 | Everywhere | Accessible from… | |
---|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ | Everywhere |
protected |
✓ | ✓ | ✓3 | Package and kids | |
Default (nothing) | ✓ | ✓ | Package | ||
private |
✓ | Same class |
The following example shows two classes in the same package. Class B
extends class A
and so it can access all the fields of the superclass except the private
ones:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.jcr.package1; public class A { public int publicField; protected int protectedField; int defaultField; private int privateField; } class B extends A { void foo() { publicField++; protectedField++; defaultField++; // compiler error: private fields are only accessible from its own class privateField++; } } |
Now take a look at the following example showing a third class C
also extending A
. However class C
belongs to a different package than class A
and so it can only access public
and protected
fields of the superclass:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.jcr.package2; import com.jcr.package1.A; public class C extends A { void foo() { publicField++; protectedField++; // compiler error: defaultField is not accessible defaultField++; // compiler error: privateFields is not accessible privateField++; } } |