A class is defined inside another class, and the class inside is called an inner class (nested class, built-in class)
Access rules for internal classes:
- Inner classes can access members in external classes directly, including private
- External class to access internal classes, you must establish an inner class object
Members in an external class can be accessed directly because the inner class holds a reference to an external class, in the format: external class name. This
Access format:
1 when an inner class is defined on the member position of an external class and is not private, it can be in an external class
You can create an inner class object directly
The format is:
The outer class name. Internal class Name Variable name = External Class object. Inner Class object
Outer.Inner in = new Outer (). New Inner ();
2 when an inner class is in a member position, it can be modified by the member modifier
For example, private: encapsulates an inner class in the outer category
Static: The inner class can be statically modified, which has the characteristics
When an inner class is modified by static, only static members in the outer class can be accessed directly, and access limitations occur
In other external classes, how to access the non-static members of internal static internal classes: New Outer.Inner (). function ();
In other external classes, how to access static members of internal static internal classes: Outer.Inner.function ();
Note: When a static member is defined in an inner class, the inner class must be static
When a static method in an external class accesses an inner class, the inner class must also be static
When to use internal classes:
When describing things, there is something inside the thing, the transaction is described in the inner class
Because the internal transaction uses the contents of the external transaction
1 classOuter2 { 3 Private intx = 3;4 5 classInner//Inner class6 {7 intx = 4;8 Static inty = 5;9 voidfunction ()Ten { One intx = 6; ASystem.out.println ("Inner:" +x);//Direct access to external class variables//6 -System.out.println ("Inner:" + This. x);//4 -System.out.println ("Inner:" +outer. This. x);//4 the } - } - - Static classStaticinner + { - voidfunction () + { A //System.out.println ("Inner:" +x);//Invalid Access Limitations atSystem.out.println ("Inner:" +y) - } - } - - voidmethod () - { inInner in =NewInner ();//methods for accessing inner classes by external classes - in.function (); to System.out.println (x); + } - } the * classInnerclassdemo $ {Panax Notoginseng Public Static voidMain (string[] args) - { theOuter out =NewOuter (); + //Out.method (); A //System.out.println (); the //direct access to members in an inner class + //Outer.Inner in = new Outer (). New Inner (); - //in.function (); $ NewOuter.Inner (). function (); $ } -}
Inner classes in Java