What is the difference between public, protected, package-private and private in Java?
In the Java programming language, the accessibility of a class, method, or field can be controlled using access modifiers. There are four access modifiers in Java:
public
: A member that is declaredpublic
can be accessed from anywhere.protected
: A member that is declaredprotected
can be accessed within its own package (i.e., its own class and any other class in the same package) and by subclasses of its class in other packages.- No Modifier (package-private): If a member has no access modifier, it is package-private. This means that the member can be accessed within its own package but not from outside the package.
private
: A member that is declaredprivate
can only be accessed within its own class.
Here is an example that demonstrates the different accessibility levels of fields in a class:
public class MyClass {
public int x; // public field
protected int y; // protected field
int z; // package-private field
private int w; // private field
}
In the example above, the x
field is public
, so it can be accessed from anywhere. The y
field is protected
, so it can be accessed within the package and by subclasses in other packages. The z
field has no access modifier, so it is package-private and can only be accessed within the package. The w
field is private
, so it can only be accessed within the MyClass
class.