Why subclass doesn't inherit the private instance variables of superclass in Java?


When you declare the instance variables of a class private, you cannot access them in another class if you try to do so a compile-time error will be generated.

But, if you inherit a class that has private fields, including all other members of the class the private variables are also inherited and available for the subclass.

But, you cannot access them directly, if you do so a compile-time error will be generated.

Example

 Live Demo

class Person{
   private String name;
   public Person(String name){
      this.name = name;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
   }
}
public class Student extends Person {
   public Student(String name){
      super(name);
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
      System.out.println("Name: "+super.name);
   }
   public static void main(String[] args) {
      Student std = new Student("Krishna");
   }
}

Compile-time error

Student.java:17: error: name has private access in Person
   System.out.println("Name: "+super.name);
                                    ^
1 error

To access the private members of the superclass you need to use setter and getter methods and call them using the subclass object.

Example

 Live Demo

class Person{
   private String name;
   public Person(String name){
      this.name = name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return this.name;
   }
   public void displayPerson() {
      System.out.println("Data of the Person class: ");
      System.out.println("Name: "+this.name);
   }
}
public class Student extends Person {
   public Student(String name){
      super(name);
   }
   public void displayStudent() {
      System.out.println("Data of the Student class: ");
   }
   public static void main(String[] args) {
      Student std = new Student("Krishna");
      System.out.println(std.getName());
   }
}

Output

Krishna
raja
Published on 10-Sep-2019 15:16:33
Advertisements