1

I got confused, as the answer suggested option A. Shouldn't aVehicle bound be viewed as a Vehicle object since the first line operated upcasting?
The question as follow:

Consider the following code snippet:

Vehicle aVehicle = new Auto();
aVehicle.moveForward(200);

If the Auto class inherits from the Vehicle class, and both classes have an implementation of the moveForward method, which statement is correct?
A) The moveForward method of the Auto class will be executed.
B) The moveForward method of the Vehicle class will be executed.
C) You must specify in the code which class's moveForward method is to be used.
D) It is not possible to determine which class it's method is called.

YI Chen Wang
  • 11
  • 1
  • 2
  • If both classes have implementation of moveForward, meaning overriding, aVehicle can access that overridden method(moveForward of Auto). – sittsering Jan 26 '23 at 05:13
  • Casting doesn't change the type of an object so when you execute an instance method it's always the one defined by that instance's type. What casting does is change the type of the reference which in turn basically just defines what the compiler can see, i.e. with `Vehicle aVehicle` the compiler sees everything that `Vehicle` provides but not what `Auto` _adds_ (I used "adds" here since `moveForward(int)` wouldn't be added but overridden or implemented - `Vehicle` already has a definition of that method). – Thomas Jan 26 '23 at 07:44

0 Answers0