Which statement is true about a static nested class?

  1. You must have a reference to an instance of the enclosing class in order to instantiate it.

  2. It does not have access to nonstatic members of the enclosing class.

  3. It's variables and methods must be static.

  4. It must extend the enclosing class.


Correct Option: B
Explanation:

To answer this question, you need to have an understanding of nested classes in Java.

A static nested class is a class that is defined inside another class, and it is marked as static. Here is an explanation of each option:

A. You must have a reference to an instance of the enclosing class in order to instantiate it. This statement is false. Unlike an inner class, a static nested class does not require an instance of the enclosing class to be instantiated. You can create an instance of a static nested class without having an instance of the enclosing class.

B. It does not have access to nonstatic members of the enclosing class. This statement is true. Since a static nested class is static, it does not have access to nonstatic members (variables or methods) of the enclosing class. It can only access static members of the enclosing class.

C. Its variables and methods must be static. This statement is false. Although the static nested class is static, it can have both static and nonstatic variables and methods. It is not required for all of its members to be static.

D. It must extend the enclosing class. This statement is false. A static nested class does not have to extend the enclosing class. It is a separate class and can have its own inheritance hierarchy.

Based on the explanations above, the correct statement about a static nested class is:

The Answer is: B. It does not have access to nonstatic members of the enclosing class.

Find more quizzes: