Java improvement articles (7) -----Detailed explanation of internal classes

The definition of one class can be placed inside the definition of another class, this is the inner class.
Inner class is a very useful feature, but it is difficult to understand and use (I haven't used inner class very much until now, and I only know a little about inner class).
The first time we meet the
inner class is very easy to understand from the outside, it is nothing more than defining a class inside a class.

public class Ass {  
    private String name ;  
    private int age;  

    public String getName() {  
        return name;  
    }  

    public void setName(String name) {  
        this.name = name;  
    }  

    public int getAge() {  
        return age;  
    }  

    public void setAge(int age) {  
        this.age = age;  
    }  

    class InnerClass{  
        public InnerClass(){  
            name = "chenssy";  
            age = 23;  
        }  
    }  
}  

Here InnerClass is the inner class. For beginners, the inner class is not used much. The rookie has not used it much (it seems to be only used in swing registration events), but with the improvement of programming ability , we will appreciate its charm, it can be used to design our program structure more elegantly. Before using inner classes, we need to understand why we use inner classes and what benefits inner classes can bring us.

one. Why use inner classes
Why use inner classes? There is such a sentence in "Think in java": The most attractive reason for using inner classes is that each inner class can independently inherit an (interface) implementation, so no matter whether the outer class has inherited a certain (interface) ) implementation, has no effect on inner classes.
In our programming, sometimes there are some problems that are difficult to solve by using interfaces. At this time, we can use the ability provided by inner classes to inherit multiple concrete or abstract classes to solve these programming problems. It can be said that interfaces only solve part of the problem, and inner classes make the solution of multiple inheritance more complete.
`public interface Father {

}

public interface Mother {

}

public class Son implements Father, Mother {

}

public class Daughter implements Father{

class Mother_ implements Mother{  

}  

} `
Actually, for this instance, we really can't see the advantages of using inner classes, but what if Father and Mother are not interfaces, but abstract classes or concrete classes? At this time, we can only use inner classes to achieve multiple inheritance.
In fact, the biggest advantage of using inner classes is that it can solve the problem of multiple inheritance very well, but if we don't need to solve the problem of multiple inheritance, then we can naturally use other coding methods, but using inner classes can also bring us The following features (from "Think in java"):
1. The inner class can use multiple instances, each instance has its own state information, and is independent of the information of other peripheral objects.
2. In a single outer class, multiple inner classes can implement the same interface in different ways, or inherit the same class.
3. The moment of creating the inner class object does not depend on the creation of the outer class object.
4. The inner class does not have a confusing "is-a" relationship, it is an independent entity.
5. The inner class provides better encapsulation. Except for the outer class, other classes cannot access it.
2. Basics
of This part mainly introduces how inner classes use the properties and methods of outer classes, and how to use .this and .new.
When we create an inner class, it has a connection with the outer class invisibly, and depending on this connection, it can access the elements of the outer class without restriction.
public class OuterClass {
private String name ;
private int age;

/**省略getter和setter方法**/  

public class InnerClass{  
    public InnerClass(){  
        name = "chenssy";  
        age = 23;  
    }  

    public void display(){  
        System.out.println("name:" + getName() +"   ;age:" + getAge());  
    }  
}  

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

}

Output:
name:chenssy ;age:23

In this application, we can see that the inner InnerClass can seamlessly access the properties of the outer class OuterClass, although it is privately decorated. This is because when we create an inner class object of an outer class, the inner class object must capture a reference to the outer class object. As long as we access the members of the outer class, we will use this reference to Select the members of the enclosing class.
In fact, in this application we also saw how to refer to the inner class: to refer to the inner class we need to specify the type of the object: OuterClasName.InnerClassName. At the same time, if we need to create an inner class object, we must use the outer class object to create the inner class through .new: OuterClass.InnerClass innerClass = outerClass.new InnerClass();.
At the same time, if we need to generate a reference to the external class object, we can use OuterClassName.this, which will generate a correct reference to the external class. Of course, this is known at compile time, without any runtime cost.
public class OuterClass {
public void display(){
System.out.println("OuterClass...");
}

public class InnerClass{  
    public OuterClass getOuterClass(){  
        return OuterClass.this;  
    }  
}  

public static void main(String[] args) {  
    OuterClass outerClass = new OuterClass();  
    OuterClass.InnerClass innerClass = outerClass.new InnerClass();  
    innerClass.getOuterClass().display();  
}
}  

Output:
OuterClass…

At this point, we need to make it clear that the inner class is a compile-time concept. Once compiled successfully, it belongs to two completely different classes from the outer class (of course, they are still related). For an outer class named OuterClass and an inner class named InnerClass, after successful compilation, there will be two class files: OuterClass.class and OuterClass$InnerClass.class.
In Java, inner classes are mainly divided into member inner classes, local inner classes, anonymous inner classes, and static inner classes.

3. Member inner class
Member inner class is also the most common inner class. It is a member of the outer class, so he can access all member properties and methods of the outer class without restrictions. Although it is private, the outer class needs to access The member properties and methods of the inner class need to be accessed through the inner class instance.
There are two points to pay attention to in the member inner class, first: there cannot be any static variables and methods in the member inner class; second: the member inner class is attached to the outer class, so the inner class can only be created after the outer class is created first. kind.

public class Ass {
private String str;

public void outerDisplay(){  
    System.out.println("outerClass...");  
}  

public class InnerClass{  
    public void innerDisplay(){  
        //使用外围内的属性  
        str = "chenssy...";  
        System.out.println(str);  
        //使用外围内的方法  
        outerDisplay();  
    }  
}  

/*推荐使用getxxx()来获取成员内部类,尤其是该内部类的构造函数无参数时 */  
public InnerClass getInnerClass(){  
    return new InnerClass();  
}  

public static void main(String[] args) {  
    OuterClass outer = new OuterClass();  
    OuterClass.InnerClass inner = outer.getInnerClass();  
    inner.innerDisplay();  
}
}  

chenssy…
outerClass…

It is recommended to use getxxx() to get the member inner class, especially when the constructor of the inner class has no parameters.

4. Local inner class
There is such an inner class, which is nested in methods and functions. The use of this class is mainly to apply and solve more complex problems. I want to create a class to assist our solution. At that time, I don't want this class to be publicly available, so a local inner class is generated. The local inner class is compiled like a member inner class, but its scope has changed, and it can only be used in the method and property. is used, the method and properties will be invalid.
I really can't think of any good examples for local inner classes, so I quote the classic example in "Think in java".
Defined in the method:
public class Parcel5 {
public Destionation destionation(String str){
class PDestionation implements Destionation{
private String label;
private PDestionation(String whereTo){
label = whereTo;
}
public String readLabel(){
return label;
}
}
return new PDestionation(str);
}

public static void main(String[] args) {  
    Parcel5 parcel5 = new Parcel5();  
    Destionation d = parcel5.destionation("chenssy");  
}  

}

定义在作用域内:
public class Parcel6 {
private void internalTracking(boolean b){
if(b){
class TrackingSlip{
private String id;
TrackingSlip(String s) {
id = s;
}
String getSlip(){
return id;
}
}
TrackingSlip ts = new TrackingSlip(“chenssy”);
String string = ts.getSlip();
}
}

public void track(){  
    internalTracking(true);  
}  

public static void main(String[] args) {  
    Parcel6 parcel6 = new Parcel6();  
    parcel6.track();  
}  

}
5. Anonymous inner class
In Swing programming, we often use this method to bind events
button2.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("You pressed the button 2");
}
});
We may find it very strange at first glance, because this inner class has no name, and we are looking at the following example:
public class OuterClass {
public InnerClass getInnerClass(final int num,String str2){
return new InnerClass(){
int number = num + 3;
public int getNumber(){
return number;
}
}; /* Note: semicolons cannot be omitted*/
}

public static void main(String[] args) {  
    OuterClass out = new OuterClass();  
    InnerClass inner = out.getInnerClass(2, "chenssy");  
    System.out.println(inner.getNumber());  
}  

}

interface InnerClass {
int getNumber();
}


Output:
5

Here we need to see a few places
1. Anonymous inner classes do not have access modifiers.
2, new anonymous inner class, this class must exist first. If we comment out that InnerClass interface, a compilation error will occur.
3. Pay attention to the formal parameters of the getInnerClass() method. The first formal parameter is modified with final, while the second one is not. At the same time, we also found that the second parameter is not used in the anonymous inner class, so when the parameter of the method needs to be used by the anonymous inner class, then this parameter must be final.
4. An anonymous inner class has no constructor. Because it doesn't even have a name to construct a method.
PS: Due to the limited space, the anonymous inner class will be introduced here. For more knowledge about anonymous inner classes, I will give a detailed introduction in the next blog (java improvement article--detailed explanation of anonymous inner classes), including why Formal parameters should be defined as final, how to initialize anonymous inner classes, etc., so stay tuned...

6. Static inner class
In the java improvement article - - the keyword static, it is mentioned that Static can modify member variables, methods, and code blocks. It can also modify inner classes. The inner classes modified by static are called static inner classes. But we prefer to call it nested inner classes. There is one of the biggest differences between static inner classes and non-static inner classes. We know that non-static inner classes will implicitly save a reference after compilation, which points to the environment where it was created, but static inner classes do not. no. The absence of this reference means:
1. Its creation does not need to depend on the surrounding class.
2. It cannot use any non-static member variables and methods of the enclosing class.

public class OuterClass {
private String sex;
public static String name = “chenssy”;

/** 
 *静态内部类 
 */  
static class InnerClass1{  
    /* 在静态内部类中可以存在静态成员 */  
    public static String _name1 = "chenssy_static";  

    public void display(){  
        /*  
         * 静态内部类只能访问外围类的静态成员变量和方法 
         * 不能访问外围类的非静态成员变量和方法 
         */  
        System.out.println("OutClass name :" + name);  
    }  
}  

/** 
 * 非静态内部类 
 */  
class InnerClass2{  
    /* 非静态内部类中不能存在静态成员 */  
    public String _name2 = "chenssy_inner";  
    /* 非静态内部类中可以调用外围类的任何成员,不管是静态的还是非静态的 */  
    public void display(){  
        System.out.println("OuterClass name:" + name);  
    }  
}  

/** 
 * @desc 外围类方法 
 * @author chenssy 
 * @data 2013-10-25 
 * @return void 
 */  
public void display(){  
    /* 外围类访问静态内部类:内部类. */  
    System.out.println(InnerClass1._name1);  
    /* 静态内部类 可以直接创建实例不需要依赖于外围类 */  
    new InnerClass1().display();  

    /* 非静态内部的创建需要依赖于外围类 */  
    OuterClass.InnerClass2 inner2 = new OuterClass().new InnerClass2();  
    /* 方位非静态内部类的成员需要使用非静态内部类的实例 */  
    System.out.println(inner2._name2);  
    inner2.display();  
}  

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

Output:
chenssy_static
OutClass name :chenssy
chenssy_inner
OuterClass name:chenssy

The above example fully demonstrates the difference between static inner classes and non-static inner classes.
The introduction of inner classes is basically over here! In fact, my knowledge of internal classes is only scratches, it is close to a rookie, and my knowledge is limited! I will use these few days to study the inner class well!

Reprinted from http://blog.csdn.net/chenssy/article/details/13024951

Guess you like

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