What is the difference between an inner class and a static nested class in Java?

Asked 2 years ago, Updated 2 years ago, 142 views

What is the main difference between an inner class and a static nested class in Java? When designing and implementing, what are the criteria for choosing one of these?

java inner-classes

2022-09-22 21:51

1 Answers

Nested classes are divided into two types: static and non-static. Nested classes declared static are called static classes. Non-static nested classes are called inner classes.

Static nested classes are accessed using the Enclosure Class name. An enclosing class is a class that encloses the nested class.

OuterClass.StaticNestedClass

For example, how to create an object in a static nested class is as follows:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

An object in the inner class exists within an object in the enclosing class. The following classes are illustrated as examples.

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

An object in the inner class can only exist inside an enclosure object. This gives you direct access to the fields and methods that objects in the enclosing class have.

To create an object in an inner class, you must first create an object in an enclosing class. The following example creates an object of an inner class within an object of an enclosing class.

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

See the Java tutorial: Java Tutorial - Nested Classes

Another way to create an object in an inner class without an object in an enclosing class:

where new A() {...} is a method of defining an inner class with static without an object from an enclosing class.


2022-09-22 21:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.