DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Can a subclass access private members of a superclass?

When you state the inst var of a class private, you cannot reach them in additional class if you attempt to do so a compile time blunder will be created.

Nonetheless, if you accede to a class that has private var, as well as all other participants of the class the private var are also inherited and accessible for the subclass.

However, you cannot reach them openly, if you do so a compile time error will be produced.

Example

class Person1{
   private String name1;
   public Person(String name1){
      this.name1 = name1;
   }
   public void displayPerson() {
      System.out.println("Person class data: ");
      System.out.println("Name of the person: "+this.name1);
   }
}
public class Student1 extends Person1 {
   public Student(String name1){
      super(name1);
   }
   public void displayStudentRecord() {
      System.out.println("Student class data: ");
      System.out.println("Name: "+super.name1);
   }
   public static void main(String[] args) {
      Student std = new Student1("Trump");
   }
}
Enter fullscreen mode Exit fullscreen mode

Compile-time error


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

To reach the private instances of the superclass you necessitly use setter and getter functions and invoke them using the subclass obj.

Example

Read more

Top comments (0)