Java Intermediate

0% completed

Previous
Next
Access Modifiers in Action

Access modifiers in Java are keywords that set the accessibility (visibility) of classes, methods, and variables. They play a crucial role in encapsulation by controlling how different parts of a program can interact with each other. Understanding and effectively using access modifiers enhances code security, maintainability, and readability by defining clear boundaries and access levels within your applications.

List of Access Modifiers

Java provides four primary access modifiers:

Image
  • public
  • private
  • protected
  • Default (no modifier)

We will cover each in-depth in this lesson.

1. "public" Access Modifier

The public access modifier allows classes, methods, and variables to be accessible from any other class in any package. It provides the highest level of accessibility, making the members accessible globally.

Example: Public Class and Public Method

In this example, the Car class and its displayInfo method are declared as public, allowing them to be accessed from any other class.

Java
Java

. . . .

Explanation:

  • public class Car:
    Declares the Car class as public, making it accessible from any other class.

  • public void displayInfo():
    Declares the displayInfo method as public, allowing it to be invoked from any class that has access to the Car class.

Output:

Car Brand: Tesla
Car Color: White
Manufacturing Year: 2023

2. "private" Access Modifier

The private access modifier restricts the visibility of classes, methods, and variables to within the class they are declared. It is the most restrictive access level, ensuring that sensitive data and implementation details are hidden from other classes.

Example: Private Variables with Restricted Access

In this example, the Car class has private variables. Attempting to access these variables directly from the Solution class will result in errors.

Java
Java

. . . .

Explanation:

  • private String brand;, private String color;, private int year;:
    Declares the brand, color, and year variables as private, restricting their direct access to within the Car class.

  • Attempting Direct Access in Solution Class:
    Uncommenting the lines trying to print car.brand, car.color, or car.year will result in compilation errors because these variables are private and cannot be accessed outside the Car class.

Note: Uncommenting the direct access lines will cause compilation errors similar to:

error: brand has private access in Car
        System.out.println(car.brand);
                           ^

3. "protected" Access Modifier

The protected access modifier allows classes, methods, and variables to be accessible within the same package and by subclasses (derived classes) in other packages. It provides a balance between public and private access levels, facilitating inheritance while maintaining some level of encapsulation.

Example: Protected Method Access Within the Same Package

In this example, the Car class has a protected method that is accessible within the same package.

Java
Java

. . . .

Explanation:

  • protected String brand;, protected String color;, protected int year;:
    Declares the brand, color, and year variables as protected, allowing access within the same package.

  • protected void displayBrand():
    Declares the displayBrand method as protected, making it accessible within the same package.

  • Access in Solution Class:
    Since Solution is in the same package as Car (no package declaration used), it can access the protected members directly.

Note: If Solution were in a different package and not a subclass, accessing protected members would result in compilation errors.

4. "Default (Package-Private)" Access Modifier

When no access modifier is specified, Java assigns the default access level, also known as package-private. Members with default access are accessible only within the same package and are not visible to classes in other packages. This access level provides a way to encapsulate class members within a package without exposing them externally.

Example: Default Access in Classes Within the Same Package

In this example, the Engine class has default access and is accessible only within the same package as the Car class. Attempting to access it from another class outside the package will result in errors.

Java
Java
. . . .

Explanation:

  • class Engine:
    Declares the Engine class without an access modifier, making it package-private. It is accessible only within the same package as the Car class.

  • Car Class:

    • private Engine engine;:
      Declares the engine variable as private, restricting its access to within the Car class.

    • engine.startEngine();:
      Accesses the startEngine method of the Engine class, which is permissible because both classes are in the same package.

  • Attempting Direct Access in Solution Class:

    • Uncommenting the lines trying to create an instance of Engine will result in compilation errors because Engine has default access and is not visible outside its package.

Output:

Toyota is starting.
Engine started.

Note: Uncommenting the direct access lines will cause compilation errors similar to:

error: Engine is not public in Car; cannot be accessed from outside package
        Engine engine = new Engine();
        ^

Through practical examples involving the Car, Engine, and Solution classes, we've demonstrated how each access modifier controls visibility and access. Additionally, we've explored how default access behaves across different packages, emphasizing the importance of proper package organization and access control in building robust Java applications. Mastery of access modifiers empowers you to design classes that are both secure and flexible, enhancing the overall quality and reliability of your software.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next