Return to site

☕🎓JAVA CERTIFICATION QUESTION: static nested class

· java,ocp

Given:

Which line fails to compile?

* line 1

* line 2

* line 3

* line 4

* All of the above

#java #certificationquestion #ocp

The wrong syntax is the one in line 3:

NestedClass nestedC = new OuterClass().new NestedClass();

Explanation:

NestedClass nestedA = new NestedClass();

- This line is valid because NestedClass is a static nested class of OuterClass, and it can be instantiated directly.

OuterClass.NestedClass nestedB = new OuterClass.NestedClass();

- This line is also valid. It explicitly mentions the outer class name (OuterClass) followed by the nested class name (NestedClass), and it creates an instance of the static nested class.

NestedClass nestedC = new OuterClass().new NestedClass();

- This line will fail to compile.

It attempts to create an instance of the nested class using the new OuterClass().new NestedClass() syntax, but NestedClass is a static nested class, not an inner (non-static nested) class.

To create an instance of a non-static nested class, you would need an instance of the outer class, but in this case, NestedClass is static.

NestedClass nestedD = new OuterClass.NestedClass();

- This line is similar to line 2 and is also valid.

It creates an instance of the static nested class without requiring an instance of the outer class.

(Note if NestedClass was not static, it would be the syntax at line 3 the right syntax.)