Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 37
Given code:
- package com.udayan.ocp;
- public class Test {
- class A {
- void m() {
- System.out.println("INNER");
- }
- }
- public static void main(String [] args) {
- //Insert statement here
- }
- }
Which statement when inserted in the main(String []) method will print "INNER" in the output?
Select 2 options.
-
A
- A a1 = new Test().new A();
- a1.m();
-
B
- Test.A a4 = this.new A();
- a4.m();
-
C
- A a3 = this.new A();
- a3.m();
-
D
- Test.A a2 = new Test().new A();
- a2.m();
Reveal correct answers
Correct answers: A, D
Explanation
There are 2 parts: 1st one is referring the name of inner class, A and 2nd one is creating the instance of inner class, A.
main method is inside Test class only, so inner class can be referred by 2 ways: A or Test.A.
As, A is Regular inner class, so instance of outer class is needed for creating the instance of inner class. As keyword 'this' is not allowed inside main method, so instance of outer class, Test can only be obtained by new Test(). Instance of inner class can be created by: new Test().new A();
Also note, keyword 'this' is not allowed static main method.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
