Java - Inheritance Access Level

Type of Access Level in Inheritance

There are four access modifiers: private, public, protected, and package-level.

The absence of the private, public, and protected access modifier is the default or package-level access.

Rule

Level
Who can access
Rule
private

no access to the outside world

If a class member is declared private, it is accessible only inside the class that declares it.
A private class member is not inherited by subclasses of that class.
public
everyone
A subclass inherits all public members of its superclass.
protected
subclasses
A protected class member is accessible inside the body of a subclass from the same package as the class or in a different package.
default or package-level access
package
package-level class member is inherited only if the superclass and subclass are in the same package.

Consider the following code

Employee class has three members: a name field, a getName() method, and a setName() method.

The name field has been declared private and hence it is not accessible inside the Manager class because it is not inherited.

The getName() and setName() methods have been declared public and they are accessible from anywhere including the Manager class.

Demo

class Employee {
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }/*from w w  w .ja v  a 2  s  .co  m*/

  public String getName() {
    return name;
  }
}
class Manager extends Employee {
}

public class Main {
  public static void main(String[] args) {
    // Create an object of the Manager class
    Manager mgr = new Manager();

    // Set the name of the manager
    mgr.setName("Mary");

    // Get the name of the manager
    String mgrName = mgr.getName();

    // Display the manager name
    System.out.println("Manager Name: " + mgrName);

    Employee emp = new Employee();
    emp.setName("Tom");
    String empName = emp.getName();
    System.out.println("Employee Name: " + empName);

  }
}

Result