Inner class
A class is defined inside another class, and the class inside is called an inner class.
Access features:
1, the inner class can access members in the outer class directly, including private members
2, the external class needs to access the objects in the inner class to which the members must establish the inner class.
Generally used for the design of classes.
When analyzing a thing, it is found that there is something in the description of the thing, and that the thing is still accessing the content of the described thing.
In this case, the other food is defined as an inner class to describe.
Direct access to members in an inner class in an external class
Class Outer {class Inner{}}class innerclassdemo{public static void Main (String [] args) {Outer.Inner in =new Outer (). New in NER ();}}
If an inner class is static. Equivalent to an external class, as an example
Class Outer {static class Inner{}}class innerclassdemo{public static void Main (String [] args) {Outer.Inner in =new outer.i Nner ();}}
Note: If a static member is defined in an inner class, the inner class must also be static.
Example of an internal class accessing an external class
class Outer {int num =3;class inner{int num =4;void Show () {int num = 5; SYSTEM.OUT.PRINTLN (num);//5system.out.println (This.num);//4system.out.println (Inner.this.num);// 4system.out.println (Outer.this.num);//3}}}class innerclass{public static void Main (String [] args) {Outer.Inner in =new Outer (). New Inner (); In.show ();}}
Why does an inner class have direct access to members in an external class?
Because the inner class holds a reference to the external class. External class name. This
Local inner class
In a local inner class, the local variable needs to be final decorated to access the local variable of the outer class. Relatively simple is not sticky code.
Anonymous inner class
Premise:
An inner class must inherit an external class or implement an interface.
Anonymous inner class: is an anonymous subclass object.
Format: New parent class or interface () {Subclass content}
Commonly used scenarios:
When a function parameter is an interface type, and there are no more than three methods in the interface. You can use an anonymous inner class as an actual parameter for delivery.
Abstract class Inter {abstract void Show1 (); abstract void Show2 ();} Class Innerclass{public static void Main (String []args) {Show (new Inter () {public void Show1 () {System.out.println ("Show1 ");} public void Show2 () {System.out.println ("Show2");}}); public static void Show (Inter in) {In.show1 (); In.show2 ();}}
Inner classes and anonymous inner classes in the Java language