Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+37 votes

When I was reading the book, I got confused about whether the method that gets called is based on the declared type of the object or the actual type. I though at one point it said that the actual type only mattered, but at another point I thought it said the the declared type mattered. Can someone clear this up for me?

asked in CSC285_Fall2018 by (1 point)

2 Answers

+15 votes
 
Best answer

So the first thing the program does in a call such as autoObject.equals(auto), in reference to figure 2.13, is look at the declared type of autoObject to determine where it will look for an appropriate signature. Since autoObject is of declared type object, the program looks in the object class and finds the signature: equals(Object o). Then when the program is determining which method to actually use, it looks at the actual type of autoObject, which is Automobile, and finds the method with the signature that it determined was necessary earlier: equals(Object o). So the method that actually gets called is the equals(Object o) within the Automobile class, even though auto is actually of type Automobile.

answered by (1 point)
selected by
+7

Yes, Riley's answer sounds right. The key thing to realize is that there are two phases to this whole process:

At compile time, the Java compiler must decide which method is the best fit based on the declared type of the object and the declared type of all parameters being passed to the method (since the compiler doesn't know what any actual types will be until runtime.) Then, at runtime, Java does not try to find the best match again (since that process could be slow/inefficient) -- instead it simply checks whether the method that it picked at compile-time was overridden by another method (with the exact same signature) in some subclass (based on the actual type of the object that the method is being invoked on.)

+12 votes
answered by (5.7k points)
...