Private vs Protected vs Final Access Modifier in Java


Whenever we declare a class we need to provide its access level so that JVM can know whether inheritance or instantiation can happen in the program and what is the scope of the class. For this we use access modifiers and these can be used with class, methods and variables etc..

  • Private access modifier restricts the method or variable access to the class only; that means the method or variable can be accessed within the same class only.

  • Protected access modifier allows access to the class and any subclass of that class, including classes in other packages.

  • Final access modifiers do not allow a class to be extended. If applied to a method then it can not be overridden by a subclass. And if a variable is declared final then it can not be assigned after initialization.

Algorithm

To implement private, protected and final access modifier, follow the steps below −

  • Step 1 − Define a class and its members i.e. methods and variables.

  • Step 2 − To declare variable or method as private use private keyword as access modifier.

  • Step 3 − To declare variable or method as protected use protected keyword as access modifier.

  • Step 4 − Define variable as final using final keyword.

  • Step 5 − Now members of the same class can access the private variable or methods.

  • Step 6 − The methods of the same class or the subclasses can access the protected variables or methods.

  • Step 7 − To access the private and protected variables outside of the class, you can use public methods that access these variables.

  • Step 8 − The methods that access private and protected variables should be declared public.

  • Step 9 − To create a constant that is accessible within the class use private and final keywords together.

  • Step 10 − To create a constant that is accessible within the class and subclass use protected and final keywords together.

Syntax

public class Way2Class {
   private int privateVariable;
   protected int protectedVariable;
   final int finalVariable = 5;

   private void privateMethod() {
      // method implementation
   }

   protected void protectedMethod() {
      // method implementation
   }
}

Approach 1: Using private access modifier

Here's the code snippet

Example

public class Main {
   private String name;
   private int age;

   public Main(String name, int age) {
      this.name = name;
      this.age = age;
   }

   private String getDetails() {
      return "Name: " + name + ", Age: " + age;
   }

   public void displayDetails() {
      String details = getDetails();
      System.out.println(details);
   }

   public static void main(String[] args) {
      Main john = new Main("John", 30);
      john.displayDetails(); // prints "Name: John, Age: 30"
      String details = john.getDetails(); // Accessing private method, results in a compile-time error
      String name = john.name; // Accessing private field, results in a compile-time error
      int age = john.age; // Accessing private field, results in a compile-time error
   }
}

Output

Name: John, Age: 30

Explanation

In the above program if we call getDetails() method and private variables outside the Employee class then we will get compile time error.

Approach 2: Using Protected access modifier

The following is a code example

Example

public class Main {
   public static void main(String[] args) {
      Car honda = new Car("Honda", "Civic", 2022, 4);
      honda.displayDetails();
   }
}

class Vehicle {
   protected String make;
   protected String model;
   protected int year;

   public Vehicle(String make, String model, int year) {
      this.make = make;
      this.model = model;
      this.year = year;
   }

   protected String getDetails() {
      return "Make: " + make + ", Model: " + model + ", Year: " + year;
   }
}

class Car extends Vehicle {
   private int numDoors;

   public Car(String make, String model, int year, int numDoors) {
      super(make, model, year);
      this.numDoors = numDoors;
   }

   public void displayDetails() {
      String details = getDetails() + ", Number of Doors: " + numDoors;
      System.out.println(details);
   }
}

Output

Make: Honda, Model: Civic, Year: 2022, Number of Doors: 4

Explanation

The following code executed without any error because we are accessing the protected variable and method inside the same package, class and subclass.

Approach 3: Using final access Modifier

Example

class Animal {
   final String species;

   public Animal(String species) {
      this.species = species;
   }

   public void makeSound() {
      System.out.println("The " + species + " makes a sound.");
   }
}

class Cat extends Animal {
   public Cat() {
      super("Cat");
   }

   @Override
   public void makeSound() {
      System.out.println("Meow!");
   }
}

public class Main {
   public static void main(String[] args) {
      Cat cat = new Cat();
      cat.makeSound();
   }
}

Output

Meow!

Explanation

The Cat class extends the Animal class and does not add any new instance variables, but it attempts to override the makeSound() method with its own implementation that simply prints out "Mawo!". However, because the makeSound() method in the Animal class is marked as final, this attempt results in a compile-time error.

Comparison Between Approaches

Private Modifier

Protected Modifier

Final Modifier

Members can be accessed within the same class as declared.

Members can be accessed within the class and subclass in the same package.

members cannot be accessed within the same class or subclass.

Interfaces can use this modifier

Interfaces can use this modifier

Interfaces can not use this modifier

Private method can be overridden

Protected method cannot be overridden

Final method cannot be overridden.

Conclusion

These access modifiers in Java are used to control the visibility of a class's members (variables, methods, and inner classes). Private limits access to members of the same class only, protected allows access to subclasses and classes in the same package, and final indicates that a member's value cannot be changed or a method cannot be overridden.

Updated on: 01-Aug-2023

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements