java inner class summary

Question: Difference between inner class and static inner class, usage scenarios?

1. Static inner classes can have static members (methods, properties), while non-static inner classes cannot have static members (methods, properties).
2. A static inner class can only access the static members of the outer class, while a non-static inner class can access all members (methods, properties) of the outer class.
3. Different instantiation methods:
(1) Instantiate member inner class ""
to create
OutClassTest oc1 = new OutClassTest();
OutClassTest.InnerClass no_static_inner = oc1.new InnerClass();
(2) Instantiate static inner class :
OutClassTest.InnerStaticClass inner = new OutClassTest.InnerStaticClass();

3. Access to inner class member properties is different:
(1) Outer class accesses inner class properties and methods:
outer class can indirectly access inner class elements through inner class references Similar: new IN().inMessage()
(2) outer class accesses static Inner class:
call the method or static variable of the inner static class, directly call
OutClassTest.InnerStaticClass.static_value
OutClassTest.InnerStaticClass.getMessage() through the class name
6. Why use inner class?

  1. The inner class can access all members of the outer class, including private properties.
  2. It is convenient to organize classes with a certain logical relationship together, and it can also be hidden from the outside world.
  3. Each inner class can independently inherit an interface, regardless of whether the outer class already inherits an interface. Thus, inner classes make the multiple inheritance solution more complete.

7. Usage scenarios of inner classes:
see for details: http://blog.csdn.net/hivon/article/details/606312 Scenario
1: When a class is no longer used by other classes except its outer classes
2: Solve some non-object-oriented statement blocks
Scenario 3: Some multi-algorithm scenarios
Scenario 4: Appropriate use of inner classes makes the code more flexible and extensible

1. What is an inner class? (generally)

Define a class in inside a class Out, this class is the inner class, and the corresponding Out becomes the outer class.

Second, the connection between the inner class and the outer class

1. The inner class is a compile-time concept. After compilation, the outer class and its inner class will generate two independent class files: OuterClass.class and OuterClass$InnerClass.class

2. The inner class can directly access the elements of the outer class, but the outer class cannot directly access the elements of the inner class

3. Outer classes can indirectly access inner class elements through inner class references

4. For static inner classes, static inner classes do not depend on outer classes, which means that objects of inner classes can be created without creating objects of outer classes. Also, a static inner class does not hold a reference to an object of the outer class

Third, the classification of inner classes

Member inner class, local inner class, anonymous inner class, static inner class.

1. Member inner class

A member inner class is an ordinary inner class. An inner class can declare access restrictions such as public, protected, and private. It can be declared as abstract for inheritance and extension by other inner classes or outer classes, or declared as static or final, or it can implement specific Interface.

If the member inner class is modified with private, it can only be accessed inside the outer class, if it is modified with public, it can be accessed anywhere; if it is modified with protected, it can only be accessed under the same package or if it inherits the outer class Access;
if it is the default access, it can only be accessed under the same package. This is a little different from external classes, which can only be modified by public and package access permissions.

The outer class uses the inner class in the usual way of class access, the only difference is that the outer class can access all the methods and properties of the inner class, including private methods and properties.

This in an inner class refers to itself like any other class. When an inner class object is created, it will have a certain connection with the surrounding object that created it, so it can access all members of the outer class without any special conditions, which can be understood as the inner class is linked to the outer class. When an inner class object is created with an outer class, the inner class object will secretly capture a reference to the outer class, so that members of the outer class can be accessed through this reference .

2. Local inner class

A local inner class is a class defined in a method or a scope. The difference between it and a member inner class is that the access of the local inner class is limited to the method or the scope.

3. Anonymous inner class

An anonymous inner class is actually a method inner class without a name, so it complies with all the constraints of a method inner class. Besides the first time, there are some points to pay attention to:

Anonymous inner classes have no access modifiers.
An anonymous inner class must inherit an abstract class or implement an interface
Anonymous inner class cannot have any static members or methods
An anonymous inner class has no constructor because it has no class name.

A common scenario for using anonymous inner classes is when the interface to be inherited or implemented has only one abstract method:

代码来自[https://www.cnblogs.com/CodingAndRiding/p/7441438.html][2]
 public class Test {
    public static void main(String[] args) {
        //4.匿名内部类
        //主要是针对那些不能直接创建对象的抽象类和接口而来的
        Student stu=new Student();
        System.out.println(stu.getClass());//class com.aowin.noname.Student
        //4.1.通过实体类创建匿名内部类对象
        //相当于创建该类的一个子类对象
        Person p=new Person(){
            public void eat(){
                System.out.println("吃八元套餐");
            }
        };
        p.eat();
        System.out.println(p.getClass());//class com.aowin.noname.Test$1//系统自动为子类命名Test$1

        Dog dog=new Dog();
        dog.bark();
        //4.2.通过抽象类创建匿名内部类对象
        //相当于定义了该抽象类的一个子类对象,并重写了抽象类中所有的抽象方法
        Animal an=new Animal(){
            public void bark(){
                System.out.println("汪汪汪...");
            }
        };
        an.bark();
        //返回的是包名加类名
        System.out.println(an.getClass());//class com.aowin.noname.Test$2

        //4.3.通过接口创建匿名内部类对象
        //相当于定义了该接口的一个实现类对象,并重写了接口中所有的抽象方法
        Sportable s=new Sportable(){
            public void sport(){
                System.out.println("打篮球");
            }
        };
        s.sport();
        System.out.println(s.getClass());//class com.aowin.noname.Test$3

    }
}
//实体类
class Person{
    public void eat(){
        System.out.println("吃饭");
    }
}
class Student extends Person{
    public void eat(){
        System.out.println("吃八元套餐");
    }
}
//抽象类
abstract class Animal{
    public abstract void bark();
}
class Dog extends Animal{
    public void bark() {
        System.out.println("汪汪...");
    }
}
//接口
interface Sportable{
    public abstract void sport();
}
4. Static inner class

The keyword static can modify member variables, methods, and code blocks. In fact, it can also modify inner classes. Internal classes modified with static are called static inner classes.
There is one biggest difference between static inner classes and non-static inner classes. We know that non-static inner classes will implicitly save a reference after compilation, which refers to the outer environment where it was created.
But static inner classes don't. Without this reference it means:

The creation of a static inner class does not need to depend on the enclosing class. You can directly create a
static inner class and cannot use any non-static member variables and methods of the enclosing class, while the inner class can

    private static String outerName;
    public  int age;

    static class InnerClass1{
        /* 在静态内部类中可以存在静态成员 */
        public static String _innerName = "static variable";
        public void display(){
            /*
             * 静态内部类只能访问外部类的静态成员变量和方法
             * 不能访问外部类的非静态成员变量和方法
             */
            System.out.println("OutClass name :" + outerName);
        }
    }
    class InnerClass2{
        /* 非静态内部类中不能存在静态成员 */
        public String _innerName = "no static variable";
        /* 非静态内部类中可以调用外部类的任何成员,不管是静态的还是非静态的 */
        public void display(){
            System.out.println("OuterClass name:" + outerName);
            System.out.println("OuterClass age:" + age);
        }
    }
    public void display(){
        /* 外部类能直接访问静态内部类静态元素 */
        System.out.println(InnerClass1._innerName);
        /* 静态内部类可以直接创建实例不需要依赖于外部类 */
        new InnerClass1().display();
        /* 非静态内部的创建需要依赖于外部类 */
        OuterClass.InnerClass2 inner2 = new OuterClass().new InnerClass2();
        /* 非静态内部类的成员需要使用非静态内部类的实例访问 */
        System.out.println(inner2._innerName);
        inner2.display();
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        outer.display();
    }
}

4. Mutual access between inner and outer classes

1. Inner class accesses outer class members

When a member inner class has a member variable or method with the same name as the outer class, a hidden phenomenon occurs, that is, the members of the member inner class are accessed by default . If you want to access the member of the same name of the outer class , you need to access it in the following form:

The outer class.this.member variable The
outer class.this.member method
But the static inner class can only access the static members of the outer class.
2. The outer class can access the inner class members. The
outer class can indirectly access the inner class element through the inner class reference.

If you want to access the members of the member inner class in the outer class, you must first create an object of the member inner class, and then access it through a reference to this object:

外部类访问内部类:
new In().inMessage();  //必须先创建内部类的对象,再访问

    class In{     //内部类
        public void inMessage() {
            System.out.println("外部类访问");  //外部类的private成员
        }
    }  

3. Access between static inner classes and outer classes (equivalent to nested classes)

(1) Static inner classes access outer classes: only static members of outer classes can be accessed, non-static members cannot be accessed!
(2) Outer class accesses static inner class members: can be accessed directly, inner class name. Attribute (method)

Reference:
https://www.cnblogs.com/latter/p/5665015.html
http://blog.csdn.net/hivon/article/details/606312

Guess you like

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