Types of access modifiers
In Java, there are several types of modifiers for controlling access to classes and members:
- private;
- package-private (also known as default, implicit);
- protected;
- public.
Only private, protected and public modifiers have the corresponding keywords. The package-private access modifier has not a keyword, but it's used when no any keyword specified.
Access modifiers for classes
A top-level class (not inner, not nested) can have one of two modifiers:
- package-private (default, no explicit modifier): a class is visible only for classes from the same package;
- public: a class is visible to all classes everywhere.
package org.hyperskill.java.packages.theory.p1;
class A {
}
The class is visible only for classes from the same package. It's not visible for classes from any other packages including:
org.hyperskill
org.hyperskill.java.packages.theory
default package
package org.hyperskill.java.packages.theory.p2;
public class B {
}
org.hyperskill
org.hyperskill.java.packages.theory
org.hyperskill.java.packages.theory.p1
default package
Access modifiers for members
A class member (a field or a method) can have one of four modifiers:
- private: a member is visible only inside the class;
- package-private: a member is visible only for classes from the same package;
- protected: a member is visible for classes from the same package and for subclasses even from other packages;
- public: a member is visible for all classes everywhere.
A class constructor can also have any of listed access modifiers.
The following table shows access to members grouped by modifiers.
Note, in this table, by a subclass we mean only a subclass from another package.
Let's consider member modifiers in more detail.
Private members
Fields are often declared private to control the access to them from the outside. In some cases, the fields are fully private and they are only used internally in the class. In other cases, the fields can be accessed via accessor methods (e.g. getters and setters).
Private methods are used to hidden internal low-level logic implementation from the other code and make public methods more concise and readable.
Here is the class Counter. It has a private field "current". The field is hidden from outside world. The field can be changed only through the method "inc()" and read by the "getCurrent()" method.
public class Counter {
private long current = 0;
public long getCurrent() {
return current;
}
public long inc() {
inc(1L);
return current;
}
private void inc(long val) {
current += val;
}
}
A class constructor can be private too. In this case, it cannot be invoked outside the class. But it can be invoked from other public constructors or from the class methods.
Package-private members
public class SomeClass {
int field;
SomeClass(int field) {
this.field = field;
}
}
public class AnotherClass {
AnotherClass() {
SomeClass clazz = new SomeClass(100);
clazz.field = 540;
}
}