I have a situation in Java that I don't really understand. It involves calling a method with different object classes.
Suppose we have a class A, and a class B which subclasses A
In another class, we have the following code:
When sillyMethod is run, the method doFoo(A) will always be called. I understand that there must be the method doFoo(A) since the compiler expects that method to exist. However why isn't doFoo(B) called at runtime?
Any explanation or links to areas where I can read up on this further would be greatly appreciated.
Java just doesn't work that way. When choosing which to call of a number of overloaded signatures, within one class, of a particular method, Java uses the compile-time type of the arguments to decide.
You're confusing this with the situation where a method in a subclass overrides a method with the same name and same signature in a superclass. In that situation, the run-time type of the object on which the method is being called determines which version is called.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
In case you missed it in Peter's reply, the compiler determines which method to call in this case. Since obj in sillyMethod() is declared as a reference to A, the compiler cannot know that it is really referencing an object of type B. This is why doFoo(A) is called rather than doFoo(B).
Consider the code below, and note the difference between overridding and overloading.
We have a Car class and a subclass of Car called VWJetta. Note that the method announce() is overridden in these classes.
In the class Garage, we have a method called polymorhpicAnnouncer, which takes a Car as an argument and calls that Car's announce method. To the compiler, this object is always a Car, and if we pass an instance of VWJetta, it will be automatically converted to type Car (upcast through method-call conversion). But when that Car's method is called, the object's true runtime type will be used to invoke the appropriate method body.
In Garage, we also have a method called signatureAnnouncer, which is overloaded to take different argument types: One method signature is for an argument type of Car, and the other is for the "more specific" argument type of VWJetta. In this situation, the compiler selects the appropriate method based on the compile-time type of the agrument being passed.
In main, we create an instance of VWJetta (its true runtime type), then pass that to the constructor for Garage, where the reference is upcast to type Car (its compile-time type within that scope)...
[ January 20, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
posted 14 years ago
Thanks for your reply. That's really cleared things up. Thanks to everyone else who posted too.
This tiny ad is wafer thin:
Programmatically Create PDF Using Free Spire.PDF with Java