First, the basic concept
1. An inner class is a class that is defined in a class. Class A requires direct access to the members of Class B, the class A can be defined into Class B, as the inner class of Class B exists.
2. An inner class can be a member of an external class and can be modified by a member modifier. (For example: Public private static)
3. A static inner class can be used as an external class.
4. Non-static inner classes allow only static constants to be defined, and other static members cannot be defined.
5. Access rules:
An inner class can directly access members in an external class because the inner class holds a reference to the external class. External class name. This
An external class needs to create an inner class object to access the inner class.
Second, the example code
1 //External class outer2 classOuter3 {4 Private Static intnum = 4;5 6 //Inner class inner_17 classinner_18 {9 Ten voidShow1 () One { ASystem.out.println ("Inner class inner_1, Show1" +num);//the inner class inner_1 can directly access members of the External class outer num - } - } the - //methods in the Outer class method access methods in the inner class inner_1 Show1 - Public voidMethod () - { +Inner_1 in =Newinner_1 (); - In.show1 (); + } A at //static inner class inner_2 - Static classinner_2 - { - voidShow2 () - { -SYSTEM.OUT.PRINTLN ("Internal static class inner_2, Show2" +num); in } - Static voidshow3 () to { +SYSTEM.OUT.PRINTLN ("Internal static class inner_2, SHOW3" +num); - } the } * $ classinner_4Panax Notoginseng { - Static Final intCount = 5;//static constants defined in an inner class the voidshow4 () + { ASystem.out.println ("Inner class inner_4, show4" +count); the } + } - } $ $ classInnerclassdemo - { - Public Static voidMain (string[] args) the { - //creates an external class object, accessing the inner class. WuyiOuter out =NewOuter (); the Out . Method (); - Wu //creates a non-static inner class object that can be accessed by other external programs by creating an external class object. -outer.inner_1 I1 =NewOuter ().Newinner_1 (); About I1.show1 (); $ - //creates a static inner class object and accesses non-static members. -outer.inner_2 i2 =Newouter.inner_2 (); - I2.show2 (); A + //creates a static inner class object and accesses static members. the Outer.Inner_2.show3 (); -Outer.inner_2 I4 =Newouter.inner_2 (); $ i4.show3 (); the the //creates a non-static inner class object and accesses a static variable. theOuter.inner_4 i5 =NewOuter ().Newinner_4 (); the i5.show4 (); - } in}
Third, the code to run
Java object-oriented partial class (Access format)