Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does following code compile and run successfully? [duplicate]

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?

like image 703
tryingToLearn Avatar asked Dec 10 '22 22:12

tryingToLearn


2 Answers

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.

like image 200
Davide Lorenzo MARINO Avatar answered Feb 16 '23 03:02

Davide Lorenzo MARINO


Access modifiers as the name suggest can only affect the accessibility of variables/methods not inheritance, you cannot access age variable directly in your Child class as it is private but it doesn't mean that it is not present for child object.

So in your case the two public methods are accessible from both classes but inside your Child class you cannot use age directly unless you change its access modifier to protected or public

For more better understanding have a look Controlling Access to Members of a Class

Also you can check Do access modifiers prevent inheritance?

like image 25
SSH Avatar answered Feb 16 '23 03:02

SSH