Java OCA OCP Practice Question 1941

Question

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

public class Main {
  public static void main(String[] args) {
    MyClass m = new MyClass();
    System.out.println(m.createInner().getSecret());
  }//from  ww  w.j  av  a2  s. c  om
}
class MyClass {
  private int secret;
  MyClass() { secret = 123; }

  class Inner {
    int getSecret() { return secret; }
  }

  Inner createInner() { return new Inner(); }
}

Select the one correct answer.

  • (a) The program will fail to compile because the class Inner cannot be declared within the class MyClass.
  • (b) The program will fail to compile because the method createInner() cannot be allowed to pass objects of the class Inner to methods outside of the class MyClass.
  • (c) The program will fail to compile because the field secret is not accessible from the method getSecret().
  • (d) The program will fail to compile because the method getSecret() is not visible from the main() method in the class Main.
  • (e) The code will compile and print 123, when run.


(e)

Note

The code will compile, and print 123, when run.

An instance of the MyClass class will be created and the field secret will be initialized to 123.

A call to the createInner() method will return the reference value of the newly created Inner instance.

This object is an instance of a non-static member class and is associated with the outer instance.

This means that an object of a non-static member class has access to the members within the outer instance.

Since the Inner class is nested in the class containing the field secret, this field is accessible to the Inner instance, even though the field secret is declared private.




PreviousNext

Related