Reputation: 223
I created the following code:
class Father {
int num = 10;
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
class Child extends Father {
public void show() {
System.out.println(num); // 20
System.out.println(this.num); // 20
System.out.println(super.num); // 20
}
}
public class Test001 {
public static void main(String[] args) {
Child child = new Child();
child.setNum(20);
child.show();
}
}
My question is why super.num will print 20? I think super.num is 10. Because variable num is unrelated between Father and Child. The variable num in Child is just a copy from Father. who can tell me why?
Upvotes: 1
Views: 1138
Reputation: 12077
The variable num
is not a copy of the variable in the parent class. It is inherited from it.
Note that num
is an instance variable. One copy of it exists per instance of Father
. Because Child extends Father
, every instance of Child
is an instance of Father
, but with the added functionality defined by the Child
class.
Upvotes: 0
Reputation: 3927
Child class inherits num from Parent class. It does not have a copy, but is truly the owner of this class.
I will give you example - Lets say parent is Fruit and num is taste - when a clild (say apple) inherits fruit - it owns the property taste. Even if "taste" was defaulted to "neutral" - apple will change taste to "appleTaste" and whenever you eat (i.e. print apple.taste) even using super, it will output "appleTaste" and not the default taste value. It is important to understand that "num" or "taste" belong to "instance" and thus, the final instance "apple" or "child" decides the value.
Gave you this example from real world to understand it via analogy and something that you can imagine.
Upvotes: 4
Reputation: 578
super.num will print 20 because those keyword "super" indicates the refernce of Parent Class,it is instantiating the sublclass. e.g.It is equivalent of ParentClass p = new ChildClass();
The refernce(p) is of Parent Class but it is still pointing to Subclass object.
Upvotes: 0
Reputation: 62874
Because variable
num
is unrelated betweenFather
andChild
That is not true. Child
extends the definition of Father
, which includes the member num
. It's accessible from child-classes, so they are allowed to change it's value (directly), or by calling the setter method (which is also accessible from sub-classes of Father
)
Upvotes: 1
Reputation:
The variable num in Child is just a copy from Father.
No it absolutely is not. num
is defined in the parent class Father
. It's accessible by Child
due to the inheritance.
When you write child.setNum(20);
it's actually the function in Father
that is used.
Upvotes: 2