Search code examples
javainheritanceencapsulation

Why does following code compile and run successfully?


I have 2 classes in JAVA:

Parent Class:

public class Parent {
    private int age;

    public void setAge(int age) {           
        this.age = age;
    }

    public int getAge(){
        return this.age;
    }       
}

Child Class:

public class Child extends Parent{      

    public static void main(String[] args){

        Parent p = new Parent();
        p.setAge(35);
        System.out.println("Parent   "+p.getAge());

        Child c = new Child();
        System.out.println("Child  " + c.getAge());         
    }
}

Output is:

  Parent   35
  Child     0

The private members are not inherited in JAVA When calling getAge() method on child class instance, why does it run successfully and even gives output as 0?


Solution

  • private member is not inherited, but public methods accessing it yes.

    When you create an object of type Child all variables of the superclass are created also if not directly usables.

    If there are public methods in the superclass you can access them from the subclass. And if those methods access the private variable values of the superclass you can indirectly via public methods access them.