An inner class is another class that is contained within a class.
The Java inner class is divided into: Member inner class, Static nested class, Method inner class, anonymous inner class.
Commonality of inner classes
(1), the inner class is still a separate class, after compiling the inner class is compiled into a separate. class file, but preceded by the class name and the $ symbol of the outer class. (2), internal classes can not be accessed in an ordinary way. An inner class is a member of an external class, so the inner class is free to access the member variables of the outer class, whether private or not. (3), the inner class is declared static, you cannot casually access the member variables of the outer class, at which point the inner class can only access static member variables of the outer class.member Inner class
1 class Outer {2class inner{3 }4 }
member inner class when you want to build an object, you must first generate an object of the outer class, and then reference the inner class through an external class:
Compiling the above code will result in two files: Outer.class and Outer$inner.class.method Inner Class
Put the class inside the method
1 class Outer {2publicvoid dosomething () {3class Inner {4publicvoid seeouter () {5}6 }7}8 }
(1), Method inner classonly within the method that defines the inner classInstantiated and cannot be instantiated outside of this method. (2), the method inner class object cannot use the non-final local variable of the method in which the inner class resides. Because the local variable of the method is on the stack, it only exists within the lifetime of the method. When a method ends, its stack structure is deleted, and local variables become history. But after the method finishes, the inner class object created inside the method may still exist in the heap! For example, if a reference to it is passed to some other code and stored within a member variable. Because there is no guarantee that the lifetime of local variables is as long as the inner class objects of the method, they cannot be used by inner class objects.
Java inner class and anonymous inner class