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.
main()
method attempts to create a new instance of the static member class Factory.main()
method.restore()
of the class Part is invalid.(e)
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.