Java Intermediate

0% completed

Previous
Next
Access Modifiers and Inheritance

When a subclass inherits from a superclass, the members of the superclass (fields, methods) remain subject to their original access modifiers. These modifiers control which members the subclass can see, as well as what’s visible to other classes inside or outside the package. Choosing the right access modifier helps maintain both security (encapsulation) and flexibility.

How Does Access Modifiers Work With Subclasses?

  • private:

    • Visible only inside the declaring class.
    • Subclasses cannot access it directly.
    • Other classes cannot access it directly.
  • Default (no modifier):

    • Visible within the same package.
    • Inaccessible to classes/subclasses in different packages.
    • Useful when you want package-level collaboration.
  • protected:

    • Visible within the same package.
    • Also visible to subclasses in other packages.
    • Not visible to unrelated classes outside the package.
  • public:

    • Visible everywhere (any package, any class).
    • Easiest to use but can reduce encapsulation if used excessively.

Below is a summary of how each access modifier affects visibility in various contexts:

Image

Example: Inheriting with Different Access Modifiers

In this example, a subclass Employee inherits from a superclass Person. Each class has fields or methods with different access modifiers, demonstrating how those members can (or cannot) be accessed.

Java
Java

. . . .

Explanation of the Code:

  • private String name;
    • Visible only within Person. Not accessible from Employee or Solution.
  • int age; (default)
    • Visible within the same package. Here, Employee can see it because it’s in the same file (and thus the same package).
  • protected int employeeId;
    • Visible within the same package and in subclasses (like Employee), even if they’re in different packages.
  • public String department;
    • Accessible everywhere.
  • public void introduce()
    • Public method. Accessible to all classes.
  • protected void showEmployeeId()
    • Protected method. Accessible within the same package or by subclasses, such as Employee.

Access modifiers directly influence which superclass members subclasses can use, as well as what’s visible to unrelated classes. By understanding private, default, protected, and public, developers can correctly balance encapsulation (data hiding) and openness (access for necessary operations). This ensures robust, secure, and organized code when working with inheritance in Java.

.....

.....

.....

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