Java OCA OCP Practice Question 2993

Question

Consider the following program:

public class Main {
    private int mem = 10;
    class Inner {
        private int imem = new Main().mem;               // ACCESS1
    }/* w  w w .ja v a 2  s.c om*/

    public static void main(String []s) {
        System.out.println(new Main().new Inner().imem); // ACCESS2
    }
}

Which one of the following options is correct?

  • a) When compiled, this program will result in a compiler error in line marked with comment ACCESS1
  • b) When compiled, this program will result in a compiler error in line marked with comment ACCESS2
  • c) When executed, this program prints 10
  • d) When executed, this program prints 0


c)

Note

an inner class can access even the private members of the outer class.

Similarly, the private variable belonging to the inner class can be accessed in the outer class.

options a) and b) are wrong because this program compiles without any errors.

the variable mem is initialized to value 10 and that gets printed by the program (and not 0) and hence option d) is wrong.




PreviousNext

Related