Skip to main content
Published on

Access Modifiers in Java

Share:

Introduction

Access modifiers in Java are essential for defining the visibility and accessibility of class members (such as attributes and methods). Through them, we can ensure that the internal components of a class are protected and exposed in a controlled manner.

Understanding Access Modifiers

Access modifiers determine the visibility of class members (attributes, methods, constructors, etc.). There are three main levels of accessibility:

  1. Public: When a member is declared as public, it can be accessed from any other class. It is the most permissive access level.
  2. Protected: A member declared as protected is accessible within its own class, by subclasses, and by classes within the same package.
  3. Private: This is the most restrictive access level. Members declared as private can only be accessed within their own class.

There is also default access (no modifier), which allows visibility only within the package it belongs to.

Why Use Access Modifiers?

Using access modifiers correctly helps with:

  • Encapsulation: Protecting class members, preventing data from being changed inappropriately.
  • Flexibility: Allows internal changes to the class without affecting the classes that use it.
  • Maintainability: Facilitates maintenance, as it limits interaction between classes.

Practical Example

Let's look at a simple example that demonstrates the use of access modifiers:

package com.caffeinealgorithm.programaremjava;

public class AccessModifiers {
  public String name = "Public";
  protected String lastName = "Protected";
  private String password = "Private";

  public void showData() {
    System.out.println("Name: " + name);
    System.out.println("Last name: " + lastName);
    System.out.println("Password: " + password);
  }
}

In the example above, name is accessible from anywhere, lastName only by subclasses and classes in the same package, and password only within the AccessModifiers class.

Conclusion

Understanding access modifiers is crucial for developing robust and well-structured Java applications. They offer an effective way to implement the encapsulation principle, one of the pillars of object-oriented programming.

Happy coding!