Can java call parent overridden method in other objects but not subtype?
You can define a new helper method in the subclass so that you don't override the original--call that--it can call the super method or not, depending on what you want.
You can't call the super method in other objects - that would violate encapsulation. The whole point is that the object controls what its overridden methods do. For instance, you might override a collection's add
method to throw an exception in certain circumstances, so it could ensure only "valid" items got added to the collection. That would be pointless if callers could just bypass it with a cast!
The only reason an object gets to call super.foo()
for itself is to enable one call to be implemented by using the parent implementation. It's up to the code in the class to make sure it only ever does that sensibly. Again, to take the add-in-a-collection example, if the collection overrides add
it would have to have some way of adding the validated item to the collection, which it would do with super.add()
.
Note that for the same reason of encapuslation, you can only call your parent implementation, not the grandparent implementation - so super.foo()
is valid, but super.super.foo()
isn't.
1:
Your question is not quite clear. What do you mean by "call through at runtime like the code"? If you are asking how instance c knows what its super class is, then yes, the class hierarchy is stored in memory, and can be accessed by the VM.
2:
Java actually does allow you to cast an instance to its parent. It's just that calling a method on an instance always uses the instance's actual class, not its compile-time class. I.e. in Java all methods are what would be called "virtual" in C++. Why this was decided I do not know.
Edit: Actually Jon Skeet explains very nicely why you cannot call a method of a super class on an instance of a sub class, so now I know :-).