(This article for reference: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)
Nested Classes
class Outerclass { ... class Staticnestedclass { ... } ...... class innerclass { ...}
Defined
Nested Classes (nested classes) are divided into two types:non-static and static, which is often referred to as inner classes, which is called static nested Classes.
Scopes and access scopes
Both nested classes are internal members of their enclosing class , andnon-static classes can refer to the private member of the wrapper class. The static classes does not have this ability. Both of the nested classes can be declared as public/protected/private/package private.
Action scenario (due to the high generalization of the text, direct reference)
- It is a-a-logically grouping classes that's only used in one place.
- It increases encapsulation.
- It can leads to more readable and maintainable code.
Static Nested Classes
Inner Classes
Shadowing (do not know the exact Chinese translation is what, "masking"? )
The original text in a very concise code to clarify the problem
Public classMain { Public Static voidMain (string[] args)throwsException {(NewOuterclass ()).NewInnerclass (). Printx (2); System.out.println ("Finish!"); }}classOuterclass {intx = 0; classInnerclass {intx = 1; Public voidPrintx (intx) {System.out.println ("X=" +x); System.out.println ("This.x=" + This. x); System.out.println ("outerclass.this.x=" + outerclass. This. x); } }}
Output:
x=2this.x=1outerclass.this.x=0finish!
Serialization
- Serialization of inner classes, including local and annonymous classes, is strongly discouraged.
- The reason is that when the compiler compile certain constructs , it produces synthetic Constructs:these is classes, methods, fields, and other Constructs that does not has a corresponding construct in the source code.
- Compatibility issues If you serialize an inner class and then deserialize it with a different JRE Implementat Ion.
Java-nested Classes