Java OCA OCP Practice Question 2984

Question

Given:

class Shape {
   public static String s = "";

   public static void fly() {
      s += "fly ";
   }/*from  ww w .  ja va 2s.c om*/
}

public class Main extends Shape {
   public static void fly() {
      s += "hover ";
   }

   public static void main(String[] args) {
      Shape b1 = new Shape();
      Shape b2 = new Main();
      Shape b3 = (Main) b2;
      Main b4 = (Main) b2;

      b1.fly();
      b2.fly();
      b3.fly();
      b4.fly();
      System.out.println(s);
   }
}

What is the result?

  • A. fly fly fly fly
  • B. fly fly fly hover
  • C. fly fly hover hover
  • D. fly hover hover hover
  • E. hover hover hover hover
  • F. Compilation fails.
  • G. An exception is thrown at runtime.


B is correct.

Note

Remember, polymorphic invocations apply only to instance methods, not static methods.




PreviousNext

Related