Java OCA OCP Practice Question 2583

Question

Which is a true statement about the following code?

public class Main { 
   static interface Shape { } 
   static class Rectangle implements Shape { } 
   static class Square extends Rectangle { } 
   public static void main(String[] args) { 
      Square c = new Square(); 
      Shape m = c; //from  w w  w .  jav  a2  s.  c  o  m
      Rectangle f = c; 
      int result = 0; 
      if (c instanceof Shape) result += 1; 
      if (c instanceof Rectangle) result += 2; 
      if (null instanceof Square) result += 4; 
      System.out.println(result); 
  } } 
  • A. The output is 0.
  • B. The output is 3.
  • C. The output is 7.
  • D. c instanceof Shape does not compile.
  • E. c instanceof Rectangle does not compile.
  • F. null instanceof Square does not compile.


B.

Note

c is an instance of Square.

It is an instance of any super classes or interfaces it implements.

In this case, those are Rectangle, Shape, and Object.

null is not an instance of any type.

Therefore, the first two if statements execute and result is 3.




PreviousNext

Related