Reputation: 101
I'm currently learning JAVA and got confused on the access in inheritance. The case below:
public class Father{
private int age;
public void setAge(int a){
age = a;
}
public void getAge(){
System.out.println(age);
}
} //End of Father
public class Son extends Father{
} //End of Son
public class Test{
public static void main(String[] args) {
Father F = new Father();
Son S = new Son();
F.setAge(40);
F.getAge();
S.setAge(20);
S.getAge();
//System.out.println(F.age);
}
} //End of Test
In the case above, "age" is a private variable in Father. Although Son extends Father, this private variable "age" is not inherited. Which means there is no variable in Son.
But when I put them into Test, running result shows "40" and "20", as if there was an int variable in Son. How to explain this?
Upvotes: 0
Views: 86
Reputation: 1842
Your setters and getters are public so they are exposed in to the sub-class Son. The code for the setter and getter is contained in the super-class Father which has access to the private field 'age' in that class definition.
If you were to change the setter and getter to private then the sub-class Son would not have access to age field in the super-class Father.
public class Father{
// only this class may access the field directly
private int age;
// this class,sub-classes and package classes may set the age
protected void setAge(int a){
age = a;
}
// you can get the age from anywhere
public void getAge(){
System.out.println(age);
}
} //End of Father
Upvotes: 0
Reputation: 8938
Private variables are still there in subclasses; they are just not visible to the subclass. Since the getAge() method is public in the superclass, and thus in the subclass, you can still invoke it to cause the private variable to be printed.
Upvotes: 0
Reputation: 234875
age
is inherited. It's just that you can't access it directly from son
.
If you want to access it directly in son
then mark it as protected
and not private
, i.e. declare
protected int age;
in the Father
class.
(By the way, the normal thing to do would be to have getAge() return an int
, and your calling function write the age to the console).
Upvotes: 2
Reputation: 5755
setAge() and getAge() are the public methods and the instance variable is being accessed through those methods, which are directly inherited. The instance variable is not being accessed directly, i.e. by direct manipulation outside methods in the class Father.
Upvotes: 0