Java OCA OCP Practice Question 1545

Question

What is the output of the following application?

package mypkg; /*  w ww.java 2 s  . com*/

public class Main { 
   private int volume = 1; 
   private class MyClass { 
      private static int volume = 3; 
      void print() { 
         System.out.print("Print("+Main.this.volume+")!"); 
      } 
   } 
   public static void main(String... eggs) { 
      Main pen = new Main(); 
      final Main.MyClass littleOne = pen.new MyClass(); 
      littleOne.print(); 
   } 
} 
  • A. Print(1)!
  • B. Print(3)!
  • C. The code does not compile.
  • D. The code compiles but the output cannot be determined until runtime.


C.

Note

The Main class includes a member inner class MyClass.

Member inner classes cannot include static methods or variables.

Since the variable volume is marked static, the member inner class MyClass does not compile, making Option C the correct answer.

Note that the variable volume referenced in the print() method is one defined in the Main outer class.

If the static modifier was removed from the volume variable in the MyClass class, then the rest of the code would compile and run without issue, printing Print(1)! at runtime.




PreviousNext

Related