14
JunAccess Modifiers in Java: Default, Private, Public, Protected
Access specifiers in Java define the visibility and accessibility of class members, allowing developers to control access to variables, methods, and constructors. Understanding access specifiers in Java is essential for implementing proper encapsulation and ensuring security in object-oriented programming. Java loops can use these access specifiers in Javato give the program security and authorization.
In this Java tutorial, we will learn about Access Specifiers in Java. We will discuss the meaning of an access specifier, give examples from real-world situations, and look at various types of access modifiers, such as default, private, protected, and public.
If you aren't clear with the following concepts, do refer to them to understand Java Access Modifiers completely: |
What is an Access Modifier in Java?
Access Modifier in Java is a keyword that defines the visibility level of classes, methods, variables, and constructors. It tells the Java compiler where a particular element can be accessed from in the program. Java has four access modifiers: public, private, protected, and default (no keyword).
- public: The element is accessible from any class in any package.
- private: The element is accessible only within the same class.
- protected: The element is accessible within the same package and in subclasses, even in different packages.
- default (no modifier): Accessible only within the same package (also called package-private).
Java Access Modifiers Overview
Modifier | Class | Package | Subclass | Other-Packages | Description |
public | ✔ | ✔ | ✔ | ✔ | Accessible from anywhere. |
protected | ✔ | ✔ | ✔ | ✘ | Accessible within the same package and subclasses, even in other packages. |
default | ✔ | ✔ | ✘ | ✘ | Accessible only within the same package. No keyword is needed; it’s the default accessibility. |
private | ✔ | ✘ | ✘ | ✘ | Accessible only within the same class. |
Key Notes:
- Subclass access for protected: It allows access when subclassing, even if the subclass resides in a different package. However, access is limited to inherited members.
- Default access (no modifier): Often called "package-private." It's the default if no access modifier is specified.
- Private: Strictly confined to the declaring class.
Read More: Top 50 Java Interview Questions |
Real-Life Example of an Access Modifier in Java
As a real-time example, we can choose Facebook, where users can control their posts.
There are three types of Access Modifiers: "Public Access Specifier," "Protected Access Specifier," and "Private Access Specifier."
- If anyone wants to make the status visible to the public, they can choose "Public Access Specifiers."
- If anyone wants to make their status visible to only their friends, it is called a "Protected Access Specifier."
- Lastly, if someone wants to make the status visible only to themselves, they can use the "Private Access Specifier."
Types of Access Modifiers in Java
There are four types of Access Modifier in Java:
- Default Access Modifier
- Private Access Modifier
- Protected Access Modifier
- Public Access Modifier
1. Default Access Modifier in Java
In Java, the default access modifier is applied automatically to classes, methods, and data members when no access modifier is specified. This indicates that specific parts are only accessible from within the package in which they are defined.
Read More: What is a Package in Java? |
Example
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.balance = 1000.0;
account.deposit(500.0);
System.out.println("Balance: " + account.balance); // Accessible because Main is in the same package
}
}
// File: BankAccount.java
class BankAccount {
double balance; // Default access modifier (package-private)
void deposit(double amount) { // Default access modifier (package-private)
balance += amount;
}
}
Explanation
The balance variable and deposit method of BankAccount in this example have default (package-private) access, meaning that Main, which is in the same package, can access them. The default access level is illustrated by the Main class, which initializes the balance, deposits money, and prints the updated balance.
Output
Balance: 1500.0
2. Private Access Modifier in Java
The private access modifier in Java is used to restrict access to class members. When a variable or method is marked as private, it can be accessed only within the same class. This helps in data hiding and encapsulation, keeping internal details secure.
Example
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(amount + " deposited successfully.");
} else {
System.out.println("Invalid amount for deposit.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println(amount + " withdrawn successfully.");
} else {
System.out.println("Invalid amount or insufficient balance.");
}
}
public void displayBalance() {
System.out.println("Current balance: " + balance);
}
public static void main(String[] args) {
// Example usage
BankAccount account = new BankAccount(1000);
account.displayBalance();
account.deposit(500);
account.displayBalance();
account.withdraw(200);
account.displayBalance();
account.withdraw(1500);
}
}
Explanation
The BankAccount class employs private access for balance to enable secure data management. Deposit and withdraw methods validate the balance, while displayBalance displays the current amount. The main method demonstrates these actions by showing how encapsulation controls and protects data within the class.
Output
Current balance: 1000.0
500.0 deposited successfully.
Current balance: 1500.0
200.0 withdrawn successfully.
Current balance: 1300.0
Invalid amount or insufficient balance.
3. Protected Access Modifiers in Java
The protected access modifier in Java allows access to class members within the same package and also to subclasses in other packages. It provides more access than private but less than public. This is commonly used when you want to share data with subclasses while still limiting access to unrelated classes.
Read More: Hierarchical Inheritance in Java |
Example
// Base class
class Vehicle {
protected String brand; // protected member variable
protected void displayDetails() {
System.out.println("Brand: " + brand);
}
}
// Derived class
class Car extends Vehicle {
private int mileage; // private member variable specific to Car
public Car(String brand, int mileage) {
this.brand = brand; // accessing protected member from superclass
this.mileage = mileage;
}
public void displayCarDetails() {
displayDetails(); // accessing protected method from superclass
System.out.println("Mileage: " + mileage);
}
}
// Main class to test inheritance and protected access
class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 30);
myCar.displayCarDetails();
}
}
Explanation
There are two classes in this Java example: Parent and Child. The notion of inheritance and protected access is shown by the reality that the Child class derives from the Parent class and can access the protected method "display()" of the Parent class thanks to the protected access modifier.
Output
Brand: Toyota
Mileage: 30
4. Public Access Modifier in Java
The public access modifier in Java allows class members to be accessed from anywhere in the program. When a method, class, or variable is declared as public, it is visible to all other classes, even in different packages. This modifier is used when you want to make something universally accessible throughout the application.
Example
// File: Main.java
class Main {
public static void main(String[] args) {
Book book = new Book();
book.title = "The Great Gatsby";
book.setAuthor("F. Scott Fitzgerald");
System.out.println("Title: " + book.title);
System.out.println("Author: " + book.getAuthor());
}
}
// File: Book.java
class Book {
public String title; // Public access modifier
private String author; // Private access modifier
public void setAuthor(String author) { // Public access modifier
this.author = author;
}
public String getAuthor() { // Public access modifier
return this.author;
}
}
Explanation
This code defines the Main and Book classes. Main creates a new instance of Book, using public methods (setAuthor) to set its title and author and public access (title and getAuthor) to obtain it. A book that allows for private access to control direct modification encapsulates the author field.
Output
Title: The Great Gatsby
Author: F. Scott Fitzgerald
Go through the following Interview articles: |
Java Access Modifiers with Method Overriding
1. Access Modifier Rules in Overriding
- Cannot reduce visibility: The overridden method in the subclass must have the same or higher visibility compared to the method in the superclass.
- Can increase visibility: For example, a protected method in the superclass can be overridden as public in the subclass.
2. Modifier Behavior with Overriding
Access Modifier in Superclass | Allowed in Subclass | Notes |
public | public | Visibility must stay the same (public). |
protected | protected, public | Visibility can increase but cannot decrease. |
default (package-private) | default, protected, public | Overriding is allowed within the same package; visibility can increase. |
private | It cannot be overridden | A private method is not inherited; it is treated as a new method in the subclass. |
3. Key Example
class SuperClass {
protected void display() {
System.out.println("Superclass display method");
}
}
class SubClass extends SuperClass {
@Override
public void display() { // Increasing visibility from protected to public
System.out.println("Subclass display method");
}
}
public class Test {
public static void main(String[] args) {
SuperClass obj = new SubClass(); // Polymorphism in action
obj.display(); // Outputs: Subclass display method
}
}
Output
Subclass display method
Note: In the above code, you have to write the file name as the class name (Test.java) |
Conclusion
In conclusion, access modifiers in Java are essential for controlling visibility and protecting data. They help in building secure, organized, and well-structured programs by limiting how different parts of the code interact. Choosing the right access modifier (private, protected, public, or default) is key to writing clean and maintainable Java code.
To deepen your understanding and enhance your skills, consider enrolling in our Free Java Certification Course, which offers comprehensive learning and certification to support your Java journey. And enhance your knowledge with our Free Technology Courses.