DEV Community

Cover image for Access modifiers in Java
Mercy
Mercy

Posted on

Access modifiers in Java

Access modifiers in Java play a crucial role in defining the visibility and accessibility of classes, methods, and variables. They are fundamental to the principles of encapsulation, which is a key concept in object-oriented programming (OOP). This blog post will delve into the four primary access modifiers in Java—public, private, protected, and default (or package-private).

Java provides four primary access modifiers:

  1. Public: Members declared as public can be accessed from any other class in any package. This is the least restrictive access level.
  2. Private: Members declared as private are accessible only within the class they are declared in. This is the most restrictive access level, ensuring that sensitive data is hidden from other classes.
  3. Protected: Members declared as protected can be accessed within the same package and by subclasses, even if they are in different packages. This modifier allows for more accessibility than default but less than public.
  4. Default (Package-Private): If no access modifier is specified, the member is accessible only within its own package. This means it cannot be accessed from classes outside its package.

Importance of Access Modifiers

  • Encapsulation: They help encapsulate the data by restricting access to certain parts of an object.
  • Security: By limiting access, they protect sensitive data from unauthorized access.
  • Maintainability: Proper use of access modifiers makes code easier to maintain and refactor.
  • Readability: They enhance code readability by clearly indicating which components are intended for external use.

1. Public

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the add method can be called from any other class:

public class TestCalculator {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 10)); // Output: 15
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Private

The private modifier restricts access to the class itself. No other class can access private members.

Example:

public class Person {
    private String name;

    private String getName() {
        return name;
    }

    public Person(String name) {
        this.name = name;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this case, the getName method cannot be accessed outside the Person class:

public class TestPerson {
    public static void main(String[] args) {
        Person person = new Person("Alice");
        // System.out.println(person.getName()); // Error: getName() has private access
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Protected
The protected modifier allows access within the same package and by subclasses even if they are in different packages.

Example:

public class Animal {
    protected void makeSound() {
        System.out.println("Animal sound");
    }
}

public class Dog extends Animal {
    public void bark() {
        makeSound(); // Accessible due to protected modifier
        System.out.println("Bark");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, makeSound can be accessed by Dog, which is a subclass of Animal:

public class TestDog {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.bark(); // Output: Animal sound \n Bark
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Default (Package-Private)
If no access modifier is specified, it defaults to package-private, meaning it is accessible only within its own package.
Example:

class DefaultClass {
    void display() {
        System.out.println("Default Access Modifier");
    }
}
Enter fullscreen mode Exit fullscreen mode

This method can only be accessed by classes within the same package:

public class TestDefaultClass {
    public static void main(String[] args) {
        DefaultClass obj = new DefaultClass();
        obj.display(); // Output: Default Access Modifier
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Best Practices for Using Access Modifiers

  1. Use Private for Variables: Always declare member variables as private to enforce encapsulation.
  2. Provide Public Getters/Setters: Use public methods to control access to private variables.
  3. Limit Public Methods: Only expose methods that are necessary for external use.
  4. Use Protected for Inheritance: Use protected for methods that subclasses need to override or access.
  5. Avoid Excessive Public Access: Be cautious with public modifiers; ask if something truly needs to be publicly accessible.

Conclusion
Understanding and effectively using access modifiers is essential for creating robust, secure, and maintainable Java applications. By controlling visibility through modifiers, we can enforce encapsulation and safeguard our code against misuse while improving its readability and maintainability. As we design our classes and interfaces, we need to consider which access level best suits our needs to promote good coding practices in our Java projects.

Top comments (0)