What is the primary difference between a static and a non-static inner class?

Study for the Java Technical Interview! Test your knowledge with multiple choice questions, each offering hints and explanations. Get ready to ace your Java exam!

Multiple Choice

What is the primary difference between a static and a non-static inner class?

Explanation:
The primary difference between a static and a non-static inner class lies in the relationship they have with the outer class instance. A non-static inner class is associated with an instance of the outer class, meaning it requires the creation of an instance of the outer class to be instantiated. This allows the non-static inner class to access instance variables and methods of its outer class directly, given that it implicitly holds a reference to the outer class's instance. In contrast, a static inner class does not have this association; it can be instantiated independently of any outer class instance. While it can access the static members of the outer class, it cannot directly access instance variables or instance methods without an explicit reference to an outer class instance. Therefore, saying that a non-static inner class may have object instances tied to the outer class effectively highlights its dependency on the outer class's instance for creation and interaction, making this choice the correct answer.

The primary difference between a static and a non-static inner class lies in the relationship they have with the outer class instance. A non-static inner class is associated with an instance of the outer class, meaning it requires the creation of an instance of the outer class to be instantiated. This allows the non-static inner class to access instance variables and methods of its outer class directly, given that it implicitly holds a reference to the outer class's instance.

In contrast, a static inner class does not have this association; it can be instantiated independently of any outer class instance. While it can access the static members of the outer class, it cannot directly access instance variables or instance methods without an explicit reference to an outer class instance. Therefore, saying that a non-static inner class may have object instances tied to the outer class effectively highlights its dependency on the outer class's instance for creation and interaction, making this choice the correct answer.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy