Java OCA OCP Practice Question 2260

Question

What is the output of the following application?

package mypkg; /*  w w w  .  java  2 s .co m*/

abstract class Shape { 
   abstract int getArea(); 
   public Shape() { 
      System.out.print("Starting..."); 
   } 
} 
public class Main { 
   abstract class Rectangle extends Shape { 
      int getArea() {return 5;} 
   } 
   private static void dress() { 
      class Square extends Rectangle {  // v1 
         int getArea() {return 10;} 
      }; 
      final Shape outfit = new Square() {  // v2 
         int getArea() {return 20;} 
      }; 
      System.out.println("Insulation:"+outfit.getArea()); 
   } 

   public static void main(String... snow) { 
      new Main().dress(); 
   } 
} 
  • A. Starting...Insulation:20
  • B. Starting...Insulation:40
  • C. The code does not compile because of line v1.
  • D. The code does not compile because of line v2.
  • E. The code does not compile for a different reason.


C.

Note

The code does not compile, so Options A and B are incorrect.

The code does not compile because the Rectangle class is an inner class defined on the instance, which means it is only accessible to be extended and used inside an instance method or by a static method that has access to an instance of Main.

Since dress() is a static method, the declaration of local inner class Square does not compile on line v1, making Option C the correct answer.

The rest of the code, including the abstract class Shape and anonymous inner class defined inside dress(), compile without issue.

If the dress() method was updated to remove the static modifier, then the code would compile and print Starting.

Insulation:20 at runtime, making Option A the correct answer.




PreviousNext

Related