1. Definition
An inner class is a class that is defined inside a class body, and the inner class is compiled into Outerclass$innerclass.class by the compiler.
class outerclass{ privateint value; class innerclass { }}
2. Features
(1) Inner classes can access properties and methods of external classes, including private properties and methods.
(2) Inner classes can be decorated with the static keyword, and you can use Outerclass.innerclass to access static internal classes. Static internal classes can only access static properties and methods of external classes.
(3) You typically create an inner class object in an external class using an inner class that creates an inner class object in another class:
If the inner class is non-static, it is necessary to create an inner class object through an external class object, such as: outerclass.innerclass innerobj = Outerobj.new innerclass;
If the inner class is static, you need to create an inner class object through Outerclass.innerclass and no longer create it through an external class object, such as: outerclass.innerclass innerobj = new Outerclass.innerclass.
3. Local inner class
If an inner class is used only in a method, you can define the inner class in the method, that is, the local inner class. Local inner classes cannot be decorated with public or private.
In addition to accessing the properties and methods of external classes, local inner classes can access local variables in the same method, but these variables must be final.
class outerclass{ privateint value; Public void method () { class localclass { } }}
4. Anonymous inner class
The anonymous inner class is more simplified on the basis of the local inner class, if only one object of the local inner class is created in the method that defines the local inner class, then the local inner class is no longer required to be named. Anonymous inner classes are generally used in conjunction with interfaces:
class outerclass{ publicvoid method () { New ActionListener () { ///This anonymous class implements the ActionListener interface
Public void actionperformed (ActionEvent e)
{
}; }}
5. Usefulness
(1) Inner classes can be hidden from other classes in the same package
(2) Anonymous inner classes are used when you want to define a callback function and want to write as little code as possible. Callbacks in Java are implemented through objects, passing a reference to an object, and then invoking a method in the object to implement the function of a callback function when appropriate.
Java Inner class