0% completed
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.
private:
Default (no modifier):
protected:
public:
Below is a summary of how each access modifier affects visibility in various contexts:
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.
private String name;
Person
. Not accessible from Employee
or Solution
.int age;
(default)
Employee
can see it because it’s in the same file (and thus the same package).protected int employeeId;
Employee
), even if they’re in different packages.public String department;
public void introduce()
protected void showEmployeeId()
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.
.....
.....
.....