Java OCA OCP Practice Question 2445

Question

Given:.

 2. public class Main {  
 3.   private int x = 4;  
 4.   public static void main(String[] args) {  
 5.     protected int x = 6;  
 6.     new Main().new Cell().slam();  
 7.   }  //from   ww w. j a va 2 s .  c  om
 8.   class Cell {  
 9.     void slam() { System.out.println("throw away key " + x); }  
10.   }  
11. } 

Which are true? (Choose all that apply.).

  • A. Compilation succeeds.
  • B. The output is "throw away key 4".
  • C. The output is "throw away key 6".
  • D. Compilation fails due to an error on line 5.
  • E. Compilation fails due to an error on line 6.
  • F. Compilation fails due to an error on line 9.


D is correct.

Note

Line 5 is declaring local variable "x", and local variables cannot have access modifiers.

If line 5 read "int x = 6", the code would compile and the result would be "throw away key 4".

Line 5 creates an anonymous Main object, an anonymous Cell object, and invokes slam().

Inner classes have access to their enclosing class's private variables.




PreviousNext

Related