Java OCA OCP Practice Question 1945

Question

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

public class Main {
  public static void main(String[] args) {
    Factory st = new Factory();
    System.out.println(st.getValue());
    Factory.Part mem = st.createPart();// w ww  .j a  v  a2s  . c  o  m
    st.alterValue();
    System.out.println(st.getValue());
    mem.restore();
    System.out.println(st.getValue());
  }

  public static class Factory {
    protected int val = 11;

    int getValue() { return val; }
    void alterValue() { val = (val + 7) % 31; }
    Part createPart() { return new Part(); }

    class Part {
      int val;

      Part() { this.val = Factory.this.val; }
      void restore() { ((Factory) this).val = this.val; }
    }
  }
}

Select the one correct answer.

  • (a) The program will fail to compile because the static main() method attempts to create a new instance of the static member class Factory.
  • (b) The program will fail to compile because the class Factory.Part is not accessible from the main() method.
  • (c) The program will fail to compile because the non-static member class Part declares a field with the same name as a field in the outer class Factory.
  • (d) The program will fail to compile because the Factory.this.val expression in the Part constructor is invalid.
  • (e) The program will fail to compile because the ((Factory) this).val expression in the method restore() of the class Part is invalid.
  • (f) The program will compile and print 11, 18, and 11, when run.


(e)

Note

The program will fail to compile, since the expression ((Factory) this).

val in the method restore() of the class Part is invalid.

The correct way to access the field val in the class Factory, which is hidden by the field val in the class Part, is to use the expression Factory.this.val.

Other than that, there are no problems with the code.




PreviousNext

Related