Java OCA OCP Practice Question 1529

Question

What is the output of the following application?

package mypkg; //from www.  ja v a  2  s  .c  o m
  
public class Main { 
   public static class Shape { 
      private enum Size {  // w1 
         TALL {protected int getHeight() {return 100;}}, 
         SHORT {protected int getHeight() {return 2;}}; 
         protected abstract int getHeight(); 
      } 
      public Size getSize() { 
         return Size.TALL; 
      } 
   } 
   public static void main(String[] stars) { 
      Main bottle = new Main(); 
      Shape q = bottle.new Shape();  // w2 
      System.out.print(q.getSize()); 
   } 
} 
  • A. TALL
  • B. The code does not compile because of line w1.
  • C. The code does not compile because of line w2.
  • D. The code compiles but the application does not produce any output at runtime.


C.

Note

The Main class includes a static nested class Shape that must be instantiated in a static manner.

Line w2 uses an instance of Main to instantiate the Shape.

While this would be allowed if Shape was a member inner class, since it is a static nested class, line w2 does not compile, and Option C is the correct answer.

If Shape was changed to be a member inner class, the code would still not compile since a member inner class cannot include static members and enums are inherently static.

The correct change would be to fix the declaration on line w2.




PreviousNext

Related