Why is it necessary for the parent to have a method in this case,
whether the child has it or not?
Your example is calling bark()
on an object statically typed as superclass
- if superclass
didn't declare the method bark()
, the compiler wouldn't know that this would be a valid call.
I am told that at compile time the
reference variable is of superclass type, so the compiler checks for
this method in the superclass at compile time; is that accurate?
Yes, in fact this is along the lines of what I said above.
When the compiler reads bark()
, how does it know where to go next? I
know the child method overrides it, but I want to know that first it
goes to the superclass method or subclass, and why.
Actually, the compiler doesn't go anywhere next. All that matters at compile time is that bark()
is a valid call on an object of type superclass
. It's only at runtime that the call is dispatched to the bark()
override declared in subclass
.
Why does the subclass need to have an access modifier of wider scope?
I'm assuming you mean the subclass's overridden method here. To clarify, it must have equal or wider access. The reason it can't have narrower access is because that would break the contract defined by the superclass.
For example if you were allowed to change bark()
to be private
in subclass
, then a call to that method theoretically shouldn't work outside of subclass
. But it needs to work, since superclass
didn't make bark()
private:
class ClassInTheSamePackageAsTheOtherTwo {
public static void main(String[] args) {
superclass refvar = new subclass();
refvar.bark(); //as far as the compiler knows, this call is valid
}
}