Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Dynamic Method Invocation (Overloading & Overriding)

+14 votes

A student asked me, via email:

When we are given Automobile auto = new Automobile();

and the operation auto.equals(sedan), where sedan is type Sedan, is the comparison happening inside of the Automobile class?  The example in the book makes it seem like that is how it should work, but I wasn't sure because there are more methods and classes in this problem.

asked Sep 11, 2016 in CSC 285 (F16) by Forrest Stonedahl (3,308 points)

1 Answer

+2 votes

Apply these steps:

a) At compile time, Java looks at the *declared type* of the object the method is being called on (auto), and find the method (inherited or overloaded) that best matches the declared types of the arguments being passed in.

b) At run time, Java checks the *actual type* of the object the method is being called on (auto), and looks to see whether the method that it tentative chose during part (a) was overridden by that class (the actual type class).  If so, it uses the overriding method.  (It doesn't look around for other methods that might be even better -- it ONLY checks to see if it's compile-time choice was overridden.)

In your example, at compile time it chooses the method Automobile.equals(Automobile), and then at runtime, it doesn't change, because the actual type of auto is the same as the declared type, so there's no way for the actual type's class to have overridden the method chosen at compile-time.

Hope that helps!

answered Sep 11, 2016 by Forrest Stonedahl (3,308 points)