Java is a popular programming language that is widely used for developing various applications. One of the key features of Java is its access modifiers, which allow developers to control the accessibility of classes, methods, and variables within their code. In this article, we will explore the different types of access modifiers in Java, namely public, protected, friendly, and private, and how they can be used to improve code reusability and maintainability.

Public Access 

The public access modifier stands as the most frequently utilized modifier in Java. It permits the accessibility of methods and variables from any location within the program, encompassing different packages. This implies that any method or variable declared as public is available for access by any other method or part of the program.

Example:

Let’s consider an example where we have two classes, Employee and SalaryCalculator. The Employee class has a public method called calculateSalary() which calculates the salary of an employee based on their hourly rate and number of hours worked. The SalaryCalculatorclass needs to use this method to calculate the salaries of all the employees in a company.

class Employee {

    double calculateSalary(double hourlyRate, int hoursWorked) {

        return hourlyRate * hoursWorked;

    }

}

class SalaryCalculator {

   static void main(String[] args) {

        Employee emp1 = new Employee();

        double salary = emp1.calculateSalary(25.50, 40);

        System.out.println("Employee 1's salary is: $" + salary);

    }

}

In the above example, the calculateSalary() method is declared as public, which allows the SalaryCalculator class to access it and use it to calculate the salary of an employee.

Protected Access 

The protected modifier permits methods and variables to be available within the same package or by subclasses of their declaring entity. This means that any method or variable declared as protected is only available within the same package or to subclasses.

Example:

Let’s continue with our previous example of the Employee class. In addition to calculating the salary, we also want to keep track of the number of hours worked by each employee. For this, we can use a protected variable called hoursWorked in the Employee class.

class Employee {

    protected int hoursWorked;

  double calculateSalary(double hourlyRate, int hoursWorked) {

        this.hoursWorked = hoursWorked;

        return hourlyRate * hoursWorked;

    }

}

Now, let’s create a subclass of the Employee class called Manager, which will have an additional method to calculate bonuses based on the number of hours worked.

class Manager extends Employee {

    double calculateBonus() {

        return hoursWorked * 10;

    }

}

In the above example, the hoursWorked variable is declared as protected, which allows the Manager class to access it and use it to calculate bonuses for employees.

Man working at computer with codes

Friendly Access 

The friendly modifier, also recognized as the default modifier, is applied when no specific modifier is stated. It permits methods and variables to be available within the same package. This implies that any method or variable declared as friendly is only available to others within the same package.

Example:

Let’s consider an example where we have two classes, Circle and Rectangle, which are part of the same package called shapes. The Circle class has a method called calculateArea()which calculates the area of a circle, while the Rectangle class has a method called calculatePerimeter() which calculates the perimeter of a rectangle.

package shapes;

public class Circle {

    double radius;

    double calculateArea() {

        return Math.PI * radius * radius;

    }

}

package shapes;

public class Rectangle {

    double length;

    double width;

double calculatePerimeter() {

        return 2 * (length + width);

    }

}

In the above example, both the Circle and Rectangle classes are declared as friendly, which allows them to access each other’s variables and methods within the same package.

Private Access 

The private modifier limits the availability of methods and variables to only within the entity where they are declared. This implies that any method or variable declared as private is only available to other methods within the same entity.

Example:

Let’s consider an example where we have a class called BankAccount, which has a private variable called balance and two methods, deposit() and withdraw(), to update the balance.

class BankAccount {

    private double balance;

 void deposit(double amount) {

        balance += amount;

    }

   void withdraw(double amount) {

        if (amount <= balance) {

            balance -= amount;

        } else {

            System.out.println("Insufficient funds.");

        }

    }

}

In the above example, the balance variable is declared as private, which means it can only be accessed and modified by the deposit() and withdraw() methods within the same class.

Comparison Table

To summarize the differences between the different types of access modifiers, we have created a comparison table below:

Modifier Class Package Subclass World 
public 
protected 
no modifier 
private 

Conclusion

In this article, we have discussed the different types of access modifiers in Java, namely public, protected, friendly, and private. We have seen how these modifiers can be used to control the accessibility of classes, methods, and variables within a program, and how they can improve code reusability and maintainability. It is important for developers to understand the differences between these modifiers and use them appropriately in their code to ensure proper encapsulation and security.