Java OCA OCP Practice Question 3205

Question

Which statements, when inserted at (1), will make the program print 1 on the standard output when executed?.


public class Main {
 int a = 1;/*from   w  ww  .  java 2  s.c  o  m*/
 int b = 1;
 int c = 1;

 class Inner {
   int a = 2;

   int get() {
     int c = 3;
     // (1) INSERT CODE HERE.
     return c;
   }
 }

 Main() {
   Inner i = new Inner();
   System.out.println(i.get());
 }

 public static void main(String[] args) {
   new Main();
 }
}

Select the two correct answers.

  • (a) c = b;
  • (b) c = this.a;
  • (c) c = this.b;
  • (d) c = Main.this.a;
  • (e) c = c;


(a) and (d)

Note

Field b of the outer class is not shadowed by any local or inner class variables, therefore, (a) will work.

Using this.a will access the field a in the inner class.

Using this.b will result in a compilation error, since there is no field b in the inner class.

Using Main.this.a will successfully access the field of the outer class.

The statement c = c will only reassign the current value of the local variable c to itself.




PreviousNext

Related