Java OCA OCP Practice Question 1817

Question

What would be the result of compiling and running the following program?.

class Vehicle {/*from  w w  w .  jav a2  s  .co m*/
 static public String getModelName() { return "V"; }
 public long getRegNo() { return 12345; }
}

class Car extends Vehicle {
 static public String getModelName() { return "T"; }
 public long getRegNo() { return 54321; }
}

public class Main {
 public static void main(String args[]) {
   Car c = new Car();
   Vehicle v = c;

   System.out.println("|" + v.getModelName() + "|" + c.getModelName() +
                      "|" + v.getRegNo()     + "|" + c.getRegNo() + "|");
 }
}

Select the one correct answer.

  • (a) The code will fail to compile.
  • (b) The code will compile and print |T|V|12345|54321|, when run.
  • (c) The code will compile and print |V|T|12345|54321|, when run.
  • (d) The code will compile and print |T|T|12345|12345|, when run.
  • (e) The code will compile and print |V|V|12345|54321|, when run.
  • (f) The code will compile and print |T|T|12345|12345|, when run.
  • (g) The code will compile and print |V|T|54321|54321|, when run.


(g)

Note

In the class Car, the static method getModelName() hides the static method of the same name in the superclass Vehicle.

In the class Car, the instance method getRegNo() overrides the instance method of the same name in the superclass Vehicle.

The declared type of the reference determines the method to execute when a static method is called, but the actual type of the object at runtime determines the method to execute when an overridden method is called.




PreviousNext

Related