Inner class detailed explanation - local inner class

definition

Inner classes within methods and scopes are called local inner classes. An anonymous inner class is a type of local inner class.

Method to realize

public class OutterType {   
    public void function() {
        /** Local inner class Inner*/
        class Inner {
            public void print() {
                System.out.println("Local inner class...");
            }
        }
    }
}

rule

Rule 1: The local inner class is similar to the local variables of the method, so the inner class cannot be accessed outside the class or in other methods of the class, but this does not mean that the instance of the local inner class has the same local variable as the method in which it is defined. life cycle.

Note that if it is a local inner class defined in a scope, it looks like this:


We define the local inner class In in an if conditional scope. Therefore, in the part outside the if, even if the function() method is not left, a compilation error will be reported, and the inner class In cannot be accessed. Therefore, it is still It is necessary to understand the meaning and access conditions of local inner classes in a broad sense, and cannot be unilaterally understood as only inner classes defined in methods.

Rule 2: It can only be used inside a method, after a class (local inner class) is defined, there is no external visibility problem, so there is no access modifier.

Rule 3: Mutable local variables cannot be used in local inner classes.

Rule 4: Member variables of the enclosing class can be accessed. If it is a static method, you can only access static-modified member variables.

Rule 5: You can use final or abstract modification.

In summary, it is the knowledge of local inner classes. In fact, the reputation of local inner classes is far less than that of anonymous inner classes, but as the parent concept of an anonymous inner class, it defines the concepts of anonymous inner classes and ordinary local inner classes and attributes, and thus can be used as knowledge additions to anonymous inner classes.

If you have any questions, please leave a message at the end of the article.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325403843&siteId=291194637