Access Modifiers
Access modifiers in Java are keywords that define the visibility and accessibility of classes, methods, variables, and constructors. They play a crucial role in encapsulation, one of the core principles of object-oriented programming (OOP). By using access modifiers, developers can control how different parts of a program interact with each other, ensuring better security, modularity, and maintainability.
Types of Access Modifiers in Java
Java provides four types of access modifiers:
- Public
- Private
- Protected
- Default (Package-Private)
Each access modifier determines the scope of accessibility for a class, method, or variable. The table below summarizes their visibility:
Modifier | Same Class | Same Package | Subclass (Different Package) | Other Classes |
|---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | No |
default | Yes | Yes | No | No |
private | Yes | No | No | No |
1. Public Access Modifier
The public modifier makes a class, method, or variable accessible from anywhere in the program. It has the widest scope of all access modifiers.
Key Points:
- A
publicclass or member can be accessed from any other class, regardless of the package. - It is commonly used for methods or variables that need to be universally accessible.
Example:
// File: Main.java
package com.example;
public class Main {
public String message = "Hello, World!";
public void displayMessage() {
System.out.println(message);
}
}
// File: Test.java
package com.test;
import com.example.Main;
public class Test {
public static void main(String[] args) {
Main main = new Main();
main.displayMessage();
// Accessible because it's public
}
}
2. Private Access Modifier
The private modifier restricts access to the class in which it is declared. It is the most restrictive access level.
Key Points:
- A
privatemember is accessible only within the same class. - It is commonly used to implement encapsulation by hiding internal details of a class.
- Getter and setter methods are often used to access private variables.
Example:
public class Account {
private double balance;
public double getBalance() {
return balance; // Getter method
}
public void setBalance(double balance) {
this.balance = balance; // Setter method
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account();
account.setBalance(1000.50); // Accessing private variable via setter System.out.println("Balance: " + account.getBalance()); // Accessing via getter
}
}
3. Protected Access Modifier
The protected modifier allows access within the same package and to subclasses in other packages. It is less restrictive than private but more restrictive than public.
Key Points:
- A
protectedmember is accessible in the same package and in subclasses (even if they are in different packages). - It is commonly used in inheritance to allow subclasses to access parent class members.
Example:
// File: Parent.java
package com.example;
public class Parent {
protected String name = "Parent";
protected void displayName() {
System.out.println("Name: " + name);
}
}
// File: Child.java
package com.test;
import com.example.Parent;
public class Child extends Parent {
public void show() {
displayName(); // Accessible because it's protected
}
}
// File: Main.java
package com.test;
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.show(); // Accessing protected method via subclass
}
}
4. Default (Package-Private) Access Modifier
If no access modifier is specified, the member is considered to have default (or package-private) access. This means it is accessible only within the same package.
Key Points:
- A default member is not accessible outside its package.
- It is commonly used for internal implementation details that should not be exposed to other packages.
Example:
// File: Example.java
package com.example;
class Example {
void display() {
System.out.println("Default access modifier");
}
}
// File: Main.java
package com.example;
public class Main {
public static void main(String[] args) {
Example example = new Example();
example.display(); // Accessible because it's in the same package
}
}
// File: Test.java
package com.test;
import com.example.Example;
public class Test {
public static void main(String[] args) {
// Example example = new Example(); // Error: Not accessible outside the package
}
}
Access Modifiers for Classes
In Java, access modifiers can also be applied to classes. However, only two modifiers are allowed for top-level classes:
- Public: The class is accessible from any other class.
- Default (Package-Private): The class is accessible only within the same package.
Example:
// Public class
public class PublicClass {
// Accessible from anywhere
}
// Default class
class DefaultClass {
// Accessible only within the same package
}
Access Modifiers and Inheritance
When a subclass inherits a class, the access modifiers of the parent class members determine their accessibility in the subclass:
publicmembers are always accessible.protectedmembers are accessible in the subclass, even if it is in a different package.defaultmembers are not accessible in subclasses outside the package.privatemembers are never accessible in the subclass.
package com.example;
public class Parent {
public String publicField = "Public";
protected String protectedField = "Protected";
String defaultField = "Default";
private String privateField = "Private";
}
package com.test;
import com.example.Parent;
public class Child extends Parent {
public void displayFields() {
System.out.println(publicField); // Accessible
System.out.println(protectedField); // Accessible
// System.out.println(defaultField); // Error: Not accessible
// System.out.println(privateField); // Error: Not accessible
}
}
Best Practices for Using Access Modifiers
- Use
privatefor sensitive data: Always declare variables asprivateand provide controlled access through getter and setter methods.- Minimize
publicmembers: Avoid exposing too manypublicmembers to maintain encapsulation.- Use
protectedfor inheritance: Useprotectedfor members that should be accessible to subclasses but hidden from other classes.- Default for internal use: Use default access for members that are only relevant within the same package.
