What is the difference between public, private and protected access modifiers in java?
n Java, access modifiers are keywords that define the scope or visibility of classes, methods, and fields in a program. There are four access modifiers in Java: public
, private
, protected
, and package-private (default).
Here’s a brief explanation of each:
Access Modifier | Visibility | Accessible from |
---|---|---|
public | Widest | Anywhere |
private | Narrowest | Same class only |
protected | Moderate | Same package and subclasses |
Default | Moderate | Same package only |
1. Public: Members (classes, methods, fields) marked as public
are accessible from any other class.
There are no restrictions on accessing public members.
public class MyClass {
public int myPublicField;
public void myPublicMethod() {
// code here
}
}
2. Private: Members marked as private
are only accessible within the same class.
They are not visible or accessible from any other class.
public class MyClass {
private int myPrivateField;
private void myPrivateMethod() {
// code here
}
}
3. Protected: Members marked as protected
are accessible within the same package and by subclasses, regardless of the package they are in.
It provides a level of access between public
and private
.
public class MyClass {
protected int myProtectedField;
protected void myProtectedMethod() {
// code here
}
}
4. Default (Package-Private): If no access modifier is specified (also known as package-private), the default access level is used.
Members with default access are accessible only within the same package.
class MyClass {
int myPackagePrivateField;
void myPackagePrivateMethod() {
// code here
}
}
It’s important to choose the appropriate access level based on the design of your classes and the desired encapsulation. Using access modifiers helps in achieving encapsulation, which is a fundamental principle in object-oriented programming.