Java OCA OCP Practice Question 1253

Question

What is the output of the following application?

package mypkg; /*from  ww w. j  av a  2s.  c o m*/
class Ship { 
        private final String drive() { return "Driving vehicle"; } 
} 
class SpaceShip extends Ship { 
        protected String drive() { return "Driving car"; } 
} 
public class ElectricSpaceShip extends SpaceShip { 
        public final String drive() { return "Driving electric car"; } 
        public static void main(String[] wheels) { 
           final SpaceShip car = new ElectricSpaceShip(); 

           System.out.print(car.drive()); 
        } 
} 
  • A. Driving vehicle
  • B. Driving electric car
  • C. Driving car
  • D. The code does not compile.


B.

Note

The drive() method in the SpaceShip class does not override the version in the Ship class since the method is not visible to the SpaceShip class.

Therefore, the final attribute in the Ship class does not prevent the SpaceShip class from implementing a method with the same signature.

The drive() method in the ElectricSpaceShip class is a valid override of the method in the SpaceShip class, with the access modifier expanding in the subclass.

For these reasons, the code compiles, and Option D is incorrect.

In the main() method, the object created is an ElectricSpaceShip, even if it is assigned to a SpaceShip reference.

Due to polymorphism, the method from the ElectricSpaceShip will be invoked, making Option B the correct answer.




PreviousNext

Related