Access Modifiers in Java
Access modifiers in Java are keywords that control the visibility and accessibility of class members (fields, methods, constructors, and nested classes) within a Java program. Java provides four access modifiers: public
, private
, protected
, and default
(also known as package-private).
Public Access Modifier
The public
access modifier is the most permissive access level. A class, method, or field declared as public
can be accessed from anywhere in the program, including other classes, packages, and subclasses.
Example:
public class MyClass {
public int publicField;
public void publicMethod() {
// This method can be accessed from anywhere
}
}
Private Access Modifier
The private
access modifier is the most restrictive access level. A class member declared as private
can only be accessed within the same class in which it is defined. It is not accessible from subclasses or other classes.
Example:
public class MyClass {
private int privateField;
private void privateMethod() {
// This method can only be accessed within the same class
}
}
Protected Access Modifier
The protected
access modifier allows access to class members within the same package and also from subclasses, even if they are in different packages.
Example:
public class SuperClass {
protected int protectedField;
protected void protectedMethod() {
// This method can be accessed within the same package
// and from subclasses
}
}
public class SubClass extends SuperClass {
// Can access the protected members from the SuperClass
}
Default (Package-Private) Access Modifier
If no access modifier is explicitly specified, the default (or package-private) access modifier is used. Class members with the default access modifier can be accessed by other classes within the same package, but not from outside the package.
Example:
class MyClass {
int defaultField;
void defaultMethod() {
// This method can be accessed by other classes
// within the same package
}
}
In summary, access modifiers in Java provide a way to control the visibility and accessibility of class members, allowing you to encapsulate your code and prevent unauthorized access. Understanding and properly using access modifiers is a fundamental aspect of Java programming and object-oriented design.