Are the private variables and private methods of a parent class inherited by the child class in Java?


No, a child class can’t inherit private members of the parent class, it can inherit only protected, default, and public members of it. If you try it gives you a compile time error as: −

Example

class Super{
   private int data = 30;
   public void display(){
      System.out.println("Hello this is the method of the super class");
   }
}
public class Sub extends Super{
   public void greet(){
      System.out.println("Hello this is the method of the sub class");
   }
   public static void main(String args[]){
      Sub obj = new Sub();
      System.out.println(obj.data);
   }
}

On executing this example it will give an compiletime error as shown below −

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
   The field Super.data is not visible
   at Sub.main(Sub.java:13)

Updated on: 30-Jul-2019

634 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements