Access Modifiers in Java with Examples

Access modifiers in Java are keywords that determine the visibility and accessibility of classes, methods, constructors, and variables within different parts of a program. They help to restrict unauthorized access to sensitive data.

In Java programming, there are four types of access modifiers:

  • Private
  • Default
  • Protected
  • Public

Types of Access Modifiers in Java

1. Private Access Modifier

The private access modifier is the most restrictive modifier that is accessible only within the same class. This modifier encapsulates the data member and restrict the access.

Example 1: Let’s write a Java program in which we will declare private members inside the class and try to access them from another class.

class Employee {
    private String empId; // Private variable
 // Declare private method.
    private void displayId() { 
        System.out.println("Employee ID: " + empId);
    }
 // Declare a public method to access private variable.
    public void setEmpId(String id) {
        empId = id;
        displayId(); // Accessible within the same class.
    }
}
public class Main {
public static void main(String[] args) {
 // Creating an object of class Employee and accessing public and private members.
    Employee emp = new Employee();
    emp.setEmpId("E1001"); // Valid
 // emp.empId = "E1002"; // Error: private access
 // emp.displayId(); // Error: private access
  }
}
Output:
       Employee ID: E1001

As you can see in the above example code, we cannot access private members of the class from another class. If we try to access them, it will result in a compile-time error, because private restricts access to within the same class only.

Example 2:

class Student {
   private String name = "Deepak";
   private void showName() {
      System.out.println("Name: " + name);
   }
}
public class Test {
public static void main(String[] args) {
    Student s = new Student();
    System.out.println(s.name); // Compile-time error
    s.showName(); // Compile-time error
    }
}

2. Default Access Modifier

The default access modifier in Java is applied when no access modifier is explicitly specified for a class, method, constructor, or variable. This modifier is also known as package-private modifier in Java.

The default access modifier allows access only within the same package. You cannot access the default members of a class from the class declared outside the package.

Note that there is no keyword for default access. It simply means no modifier is specified.

Example 3: Let’s write a simple Java program in which we will declare class, variable and method with default access modifier in a class.

class MyClass { // default access
    int number = 100;        // default access
    void show() {            // default access
        System.out.println("Number: " + number);
    }
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    obj.show();
  }
}
Output:
      Number: 100

Example 4:

package accessModifiersProgram;
class Employee { // default class
    int empId = 101;         // default field
    void displayId() {       // default method
        System.out.println("Employee ID: " + empId);
    }
}
public class MainClass {
    public static void main(String[] args) {
        Employee e = new Employee();  // allowed (same package)
        e.displayId();                // allowed
    }
}
Output:
      Employee ID: 101

In this example, we have defined two classes within the same package. Therefore, we can access members of the class Employee from the another class MainClass.

What Happens If Accessed from Another Package?

Let’s try accessing it from outside the package.

package anotherPackage;
import accessModifiersProgram.Employee; // It will not compile.

public class AccessTest {
    public static void main(String[] args) {
        Employee e = new Employee();  // Compile-time error
        e.displayId();                // Compile-time error
    }
}

3. Protected Access Modifier

The protected access modifier in Java is more accessible than private and default, but more restricted than public. You can apply this modifier with variables, methods, or constructors of a class.

The protected access modifier is accessible within the same package as well as subclasses (i.e. derived classes) even if they are in different packages.

Example 5: Let’s write a Java program where we will access the protected members in the same package.

package mypackage;
class A {
    protected void message() {
        System.out.println("This is a protected method.");
    }
}
class B {
public static void main(String[] args) {
     A obj = new A();
     obj.message();  // Allowed (same package)
  }
}
Output:
      This is a protected method.

Example 6: Java Program to access protected members in a different package through inheritance.

package animals;
public class Animal {
    protected void sound() {
        System.out.println("Animal makes sound.");
    }
}
package pets;
import animals.Animal;
public class Dog extends Animal {
    public void bark() {
        sound();  // Allowed (inherited protected method)
    }
  public static void main(String[] args) {
     Dog d = new Dog();
     d.bark();
  }
}
Output:
      Animal makes sound.

What If We Try Accessing protected Without Inheritance?

package pets;
import animals.Animal;
public class Test {
public static void main(String[] args) {
    Animal a = new Animal();
    a.sound();  // Compile-time error: 'sound()' has protected access
  }
}

Since we are trying to access protected method through an object without extending the class, so it fails.

Key Points for Protected Access Modifier

  • Access within the same class – Yes
  • Access within the same package – Yes
  • Access in subclass (same pkg) – Yes
  • Access in subclass (diff pkg) – via inheritance only
  • Access in non-subclass (diff pkg) – No

4. Public Access Modifier

The public access modifier is a least restrictive modifier which is accessible from anywhere within same class, package, subclass, or other packages. It is mainly used to expose API to other packages or modules.

Example 7:

package com.math;
public class Calculator {
   public int add(int a, int b) {
      return a + b;
   }
}
package com.test;
import com.math.Calculator;
public class Main {
public static void main(String[] args) {
    Calculator calc = new Calculator();
    System.out.println(calc.add(5, 3)); // Valid (public access)
  }
}
Output:
      8

Comparison of Access Modifiers in Java

Look at the below table for comparison among access modifiers in Java.

Access ModifierSame ClassSame PackageSubclass (Other Package)Other Package
privateYesNoNoNo
default (none)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Access Modifiers in Different Contexts

The below table shows that which access modifiers are applicable to top-level class and nested class.

ModifierTop-Level ClassNested Class
publicYesYes
defaultYesYes
protectedNoYes
privateNoYes

Quiz: Test Your Knowledge on Access Modifiers

Question 1. Which modifier allows visibility only within the same class?

  • A) public
  • B) protected
  • C) private
  • D) default

Answer: C) private

Question 2. Can a top-level class be declared private?

  • A) Yes
  • B) No

Answer: B) No

Question 3. Which modifier allows access in subclasses of different packages?

  • A) private
  • B) default
  • C) protected
  • D) public

Answer: C) protected

Question 4. What is the default modifier if none is specified?

  • A) private
  • B) public
  • C) protected
  • D) default (package-private)

Answer: D) default

Question 5. Which of the following statement is correct?

  • A) You can override a private method.
  • B) You can reduce visibility while overriding.
  • C) You can override a public method with a protected one.
  • D) You must maintain or increase visibility while overriding.

Answer: D) You must maintain or increase visibility.

FAQs on Access Modifiers in Java

1. What is the default access modifier in Java?

If no modifier is specified with a class, variable, method or constructor, Java uses package-private (default) access.

2. Can a method declared with private access modifier be inherited?

No, a method declared with private access modifier methods cannot be inherited by subclasses.

3. Can we access protected members outside the package?

Yes, we can access private members outside the package only through subclass inheritance, not via object references.

4. Is it good practice to make fields public?

No. Always prefer private fields with public getters/setters to ensure encapsulation.

5. Can a constructor be protected in Java?

Yes. Protected constructor is useful in abstract classes and inheritance patterns.

References:

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *