In Java
, public
, private
, and protected
are access modifiers used to control the accessibility of classes, methods, and variables.
public#
- Accessible from anywhere
- Can create references to this member in any other class.
public class MyClass {
public int myPublicVariable;
}
private#
- Accessible only within the class that defines it.
- Other classes cannot directly access this member.
public class MyClass {
private int myPrivateVariable;
private void myPrivateMethod() {
// Available only in MyClass
}
}
protected#
- Accessible in other classes in the same package and all subclasses.
- Suitable for members of classes that need to be inherited.
public class MyClass {
protected int myProtectedVariable;
}
Default Access Modifier#
The default access modifier (no modifier used) allows access within the same package.
class MyClass {
int myDefaultVariable; // Default access modifier
}
Summary#
public
: Accessible from anywhereprivate
: Accessible only within the classprotected
: Accessible in the same package and subclasses- Default: Accessible within the same package