nested Classes and inner Classes in Java
Java has the concept of nested classes (Nested Classes) and inner classes (Inner Classes).
Nested classes (Nested Classes) are divided into two types: static and non-static, statically and non-static, static nested classes we call static nested classes (static Nested Classes), Non-static nested classes we call the inner class (inner classes).
Static nested classes We can say this:
OuterClass.StaticNestedClass
Let's say we create a static nested class:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
There is no semantic difference between statically nested inner classes and other classes, the meaning of the existence of a static nested class is that it can directly obtain the static member variables of its outer class, and the meaning of using nested static classes is actually not large.
The inner class is represented as follows:
class OuterClass { ... class InnerClass { ... }}
An inner class object exists as an object attached to its outer class, that is, if we are to create an object of an inner class, we first have to create an object of the outer class, and then we can create an object of the inner class, and the inner class gets the field (fields) and method (methods) of the outer class directly. Create inner classes in the following ways:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
An inner class cannot define a static variable (except static final) because it relies on an object of an external class.
So, the difference between a static nested class and an inner class is:
A static nested class does not hold an application for an external class, whereas an inner class holds a reference to an external class.
The instantiation of a static nested class does not require an instance of the subclass, and an instantiation of the inner class requires an instance of the subclass first.
A static nested class cannot get a member variable of an outer class (only its static member variable), and an inner class can still get its variable (whether it is static or not) even if its member variable is private.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nested Classes and inner Classes in Java