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
?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With