Java OCA OCP Practice Question 1947

Question

What will be the result of compiling and running the following program?.

public class Main {
  public static void main(String[] args) {
    MyOutterClass.MyInnerClass obj = new MyOutterClass().new MyInnerClass();
  }/*from ww w. j  av  a2s. c o m*/
}

class MyClass {
  int val;
  MyClass(int v) { val = v; }
}

class MyOutterClass extends MyClass {
  int val = 1;
  MyOutterClass() { super(2); }

  class MyInnerClass extends MyClass {
    int val = 3;
    MyInnerClass() {
      super(4);
      System.out.println(MyOutterClass.this.val);
      System.out.println(MyInnerClass.this.val);
      System.out.println(super.val);
    }
  }
}

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will compile and print 2, 3, and 4, in that order, when run.
  • (c) The program will compile and print 1, 4, and 2, in that order, when run.
  • (d) The program will compile and print 1, 3, and 4, in that order, when run.
  • (e) The program will compile and print 3, 2, and 1, in that order, when run.


(d)

Note

The program will compile without error, and will print 1, 3, 4, in that order, when run.

The expression MyOutterClass.this.val will access the value 1 stored in the field val of the (outer) MyOutterClass instance associated with the (inner) MyInnerClass object referenced by the reference obj.

The expression MyInnerClass.this.val will access the value 3 stored in the field val of the MyInnerClass object referenced by the reference obj.

The expression super.val will access the field val from MyClass, the super class of MyInnerClass.




PreviousNext

Related