Reputation: 1342
I am asking this here because I really don't know how I should Google this. I need a confirmation of something that I probably figured out today. Some days ago I thought that if an object inherits a method of its father it means that it basically "has" the method in its code. But then I asked what if we do this:
class B extends A {
public B() {
}
public int getValue() {
return 2 * super.getValue();
}
}
class C extends B {
public C() {
}
public int getValue(int b) {
return 5 * b;
}
}
And lets say there is a class A that has the getValue()
method too. Now an object of class C uses "its" getValue()
method (without parameter) that it has inherited from B.
But super.getValue()
still refers to class A, even though the method calling it was inherited.
Inheritance does not mean that class C "has" the method in its code, but that it can use it from B, right? super()
still refers to the superclass of its "original" class.
Is that insight correct?
Upvotes: 2
Views: 278
Reputation: 122026
Inheritance does not mean that class C "has" the method in its code, but that it can use it from B, right?
Yes.
super() still refers to the superclass of its "original" class.
Yes. You are correct. super
always refers to the Parent class of where it is being used. In this case it is being used in B and it's Parent is A. So referring to there.
Upvotes: 2
Reputation: 394146
A sub-class can override any non-private method of its super-class. If it doesn't override them, it inherits the implementation of these methods from its super-class.
Therefore you can say that the sub-class "has" access to all the non-private methods of all of its ancestors. And from a reference to an instance of a sub-class you can invoke any accessible (based on the access modifiers) method of the sub-class or any ancestor of the sub-class.
The super
keyword allows you to invoke a method implementation of the super-class from the sub-class. This way you can override the implementation of a method of the super-class, but still execute the implementation of the super-class too.
In your class B :
This implementation overrides the getValue()
of A :
public int getValue() {
return 5;
}
While this implementation overrides the getValue()
of A, but still uses its logic :
public int getValue() {
return 2 * super.getValue();
}
Of course, you can't implement both in the same class, since they have the same signature.
Upvotes: 0