Access Modifiers in Java
Access Modifiers in Java
In Java, access modifiers are keywords that control the visibility and accessibility of classes, fields, methods, and other members within a class or package.
1. Public Access Modifier
The public
access modifier makes members accessible from anywhere, whether inside or outside the class and in any package.
public class PublicExample {
public int publicField;
public void publicMethod() {
// Code here
}
}
2. Protected Access Modifier
The protected
access modifier allows access within the same class, subclasses (even if they are in different packages), and classes within the same package.
public class Parent {
protected int protectedField;
}
public class Child extends Parent {
void childMethod() {
protectedField = 10; // Accessing protected field from subclass
}
}
3. Default (Package-Private) Access Modifier
The default access modifier, which is applied when no modifier is specified, restricts access to within the same package.
class DefaultExample {
int defaultField; // Default access modifier
void defaultMethod() {
// Code here
}
}
4. Private Access Modifier
The private
access modifier restricts access to only within the same class. It is the most restrictive modifier.
public class PrivateExample {
private int privateField;
private void privateMethod() {
// Code here
}
}
Using these access modifiers appropriately helps in encapsulation and maintaining the integrity of your code.