Deleted User 3513 wrote:
My train of thought in this questions is:
1) Game g = new Soccer();
- use the version of play() method in Soccer class, but verify if it is also in Game. Check if it is a legal overridden/shadowed method.
Your thought process is incorrect because you are mixing rules of compilation and rules of execution. When you say, "use the version of play() method in Soccer class", you need to understand that compiler doesn't know what object will the variable g point to at the time of execution. Thus, the compiler cannot decide this. It is the job of the JVM to decide which version of play method to execute.
When you say, "Check if it is a legal overridden/shadowed method. ". The compiler checks this when it compiles Soccer class. When the compiler encounters the statement Game g = new Soccer(); the only thing it needs to decide is whether it is ok for g to refer to an object of class Soccer. That's it. Since Soccer is a subclass of Game, compiler decides that yes, this assignment is valid.
- should still use Soccer's version of play()
- In addition, (pls verify this) if the version from the super class throws an exception, it should consider the same behavior(being handled or thrown/)
Again, you are mixing compilation and execution. The compiler only knows that g will always refer to a Game. Whether it is actually an instance of Game class or an instance of a subclass of Game is irrelevant for the compiler. As far as the compiler is concerned g will point to a Game (it could be Soccer also, but compiler doesn't care because Soccer is also a Game). Compiler will take all decisions based on the declared type of g, which is Game.
Now, since the play method as declared in Game declares that it may throw a checked exception, the compiler has to check whether the call is wrapped in a try/catch block or not. If not, whether there is a throws clause in the encompassing method or not. If neither is there, then it will refuse to compile the code.
Should same thinking applies to question: enthuware.ocajp.i.v8.2.1117? Also, please add tips in my train of thought if I missed out something. Thanks in advance.
You can now apply the same concept to 2.1117 and see how that works.
other notes: "which method will be used depends on the actual class of the object that is referenced by the variable."