About Java inner classes

  Remember when just learning the inner class, often for various internal and external class category silly could not tell, until then that is how the same thing, but as time goes by, and then to say what it is all about review is not up, so this will be a review of the internal class.

  Definition of the class is internal 可以将一个类的定义放在另一个类的定义内部, internal class is a very useful feature, which allows us to some logic related classes are grouped together, and may control the visibility located inside the class. For all kinds of inner classes mentioned above, we can roughly be divided into the following classification of pictures:

Inner classes

Inner classes

  Can be seen from the above figure, the inside inner class into static and non-static inner class, rather than static internal class can be divided into partial inner and anonymous inner classes, we inclusions inside the outer class called class , on the following:

class OuterClass {
    ...
    // 静态内部类
    static class StaticInnerClass {
        ...
    }
    // 非静态内部类
    class InnerClass {
        ...
    }
}
复制代码

  Class may be used or an external public default permissions modified package, and internal class can use private, protected, public authority, and the packet is modified. Use inner classes and we usually use the general category no different, 此外当生成内部类对象的时候,内部类持有当前外部类的引用,通过这个引用它可以访问外部类所有的成员变量,包括私有变量that is actually inside it in class and outside of class instance objects are associated, it does not exist independently of external instance of the class alone, we may wonder, it is how and external classes associated with it? In fact, when the compiler generates Java bytecode by adding a non-static inner class constructor, so that reference to an external class obtained during instantiation.

  You need to hold an external class object when building the internal class reference since then in order to create an internal class object will be created inside the class object using the object outside the class, as follows:

public class OuterClass {
    public class Inner {}
    public static void main(String[] args) {
        OuterClass out = new OuterClass();
        OuterClass.Inner in = out.new Inner();
        // 也可以使用这种方式进行创建
        Inner oin = out.new Inner();
    }
}
复制代码

Static inner classes

  When we do not want to have contact between the inner class object and its external object, we can declare the inner class as static, so it becomes a static inner classes, since there is no external object and any associated, so it is not need to rely on the external object, so it can not access non-static members of the outer class, can only access static members outside of class, in addition to internal static and non-static inner classes are also slightly different when creating:

// OuterClass 为外部类,类含有静态内部类 S 以及非静态内部类 I
OuterClass out = new OuterClass();
// 创建静态内部类
out.S staticClass = out.S();
// 创建非静态内部类
out.I in = out.new I();
复制代码

  Here be a summary of the internal static and non-static inner classes:

  1. Static inner class can have static members, rather than static inner classes can not have static members;
  2. Static inner class can access a static class variable external, non-static variable inaccessible outside the class;
  3. Non-static member non-static inner classes can access non-static variable outside the class;
  4. Create a static inner class does not depend on external class, rather than static inner classes must rely on creating external class that is created;

Partial inner class

  If an inner class only in one approach, then we can define the class in the interior of the method, this class is called internal local inner classes, whose scope is limited to the zone method, as follows:

public class OuterClass {
    
    public void show() {
        System.out.println("外部类方法");
    }   
    
    public void showFunctionClass() {
		class FunctionClass {
			private void show() {
				System.out.println("我是局部内部类");
			}
		}
        FunctionClass FunctionClass = new FunctionClass();
		FunctionClass.show();
	}
    
    public static void main(String[] args) {
        OuterClass out = new OuterClass();
		out.show();
		out.showFunctionClass();
    }
    
}

// 运行结果:
//外部类方法
//我是局部内部类
复制代码

  In addition, local inner class note the following:

  1. Local interior Foreigners are hidden and can only be accessed by creating a method of this class;
  2. Local inner classes are not allowed access modifier;

Anonymous inner classes

  Is not anonymous inner classes class name of a local class, anonymous inner classes such that instances of class definitions and simultaneously, it is usually used to simplify coding, and because it does not name the class constructor does not exist, the following two small experiments to learn how to use anonymous inner class:

public interface Person {
    public void eat();
}

public class Child implements Person {
    @Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("eat...");	
	}
	
	public static void main(String[] args) {
		Child child = new Child();
		child.eat();
	}
}
复制代码

  It is no use longhand anonymous inner class to implement the interface and then override the method in which, finally instantiate the object and call the method, in front of us when it comes to anonymous inner classes can simplify the code, then the next look at the same example using anonymous internal class how to write:

public class Child  {
	public static void main(String[] args) {
		new Person() {
			@Override
			public void eat() {
				// TODO Auto-generated method stub
				System.out.println("eat...");
			}
		}.eat();	
	}
}
复制代码

  Such anonymous inner classes will be introduced into the interface direct overwrite method, it is omitted to write a class 所以只要是一个类是抽象类或者是一个接口,那么其子类方法或接口方法都可以使用匿名内部类来实现, anonymous inner classes scenario is typical for the Thread class or Runnable interface to achieve multithreading. Also, note that if you use anonymous inner class object defined in its exterior, the compiler will require that the variable must be final, reason is to maintain the consistency of the parameters.

Why inner class

  Here, we find out about the relevant knowledge within the class, which in the "Thinking in Java" a book the author comes to internal reasons most attractive are:

Each inner class can independently inherit from an implementation (interface), so regardless of whether the enclosing class inherits an implementation (interface), for inner classes are not affected.

  See here, I want to say that the master is the master, say I look ignorant to force the (too dishes), there are summarized under the following points:

  • Data access method within the class where the class definition of the scope, including the private modifier private data;
  • Inner class can be hidden to other classes in the same package;
  • Java inner classes can solve single inheritance of defects;
  • For a large number of callbacks redundancy code may be achieved by anonymous inner classes;


Reference: "Thinking in Java"

Interpolation information

Guess you like

Origin juejin.im/post/5d063b80f265da1bbc6fd425