Internal classes in Java (member internal classes, static internal classes, local internal classes, anonymous internal classes)

Keywords: Java network Programming

Internal classes in Java (member internal classes, static internal classes, local internal classes, anonymous internal classes)

Let's start with the following passage: human beings are made up of brain, limbs, organs and other body results. The heart that makes up our human body also has its own attributes and behaviors (blood, beating). Obviously, we can't express a heart unilaterally by attributes or methods here, but we need a kind of heart. But this kind of heart depends on the existence of human beings (because the heart can't live without human body, of course, regardless of the advanced technology of modern society, only in normal circumstances). The heart needs to be written in the human body. Internal classes are equivalent to one of the organs.

First, look at what an internal class is: define another class within the class. Yes, the definition is so simple. If a class Inner is redefined inside the class Outer, Inner is called an internal class, while Outer is called an external class. Internal classes are defined in the following format:

Name of external class of public class{
    // Members of external classes
    Name of inner class of public class{
             // Membership of internal classes
    }
}

What are the benefits of using internal classes?

1) Realizing multiple inheritance;

2) Internal classes can be well hidden: general non-internal classes are not allowed to have private and protected privileges, but internal classes can

3) Reduce the size of bytecode files generated by compiling class files

 

The disadvantage of using internal classes: making the program structure unclear.

 

Internal classes also generate. class files after compilation, but the file name is: external class name $internal class name.

Types of internal classes: member internal classes, static internal classes, local internal classes, anonymous internal classes. The following is a detailed study of the specific use of these four internal classes.

I. Internal Classes of Members

1. Membership inner class is also called instance inner class. Application: Every external class object needs an instance of an internal class, which cannot be separated from the existence of an external class (equivalent to the heart to the human body).

2. The characteristics of internal classes of members:

Existing as a member of an external class, juxtaposed with the attributes and methods of the external class

Members'internal classes hold references to external classes

static variables and methods cannot be defined in member inner classes

3. Use format:

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

Code demonstration 1:

/*
 * Membership inner class
 */
public class Body {
    String arm;
    String leg;
    String blood;
    public Body(String arm, String leg, String blood) {
        super();
        this.arm = arm;
       this.leg = leg;
        this.blood = blood;
    }
    //Internal class Heart
    class Heart{
        String name;
         void work() {
            System.out.println("The heart is giving"+arm+leg+"transport"+blood);
        }
     };
}
public class Test {
    public static void main(String[] args) {       
        Body body=new Body("Two arms","Two legs","blood");
        Body.Heart  heart=body.new Heart();
        heart.work();
    }
}

Operating screenshots:

 

Code demonstration 2:

/*
 * Membership inner class
 */
public class Outer {

    private String name="Hello World";
    
    public class Inner{
        public void print(){
            System.out.println(name);
        }
    };
    public void print(){//Defining external class methods
        new Inner().print();//Calling methods through instantiated objects of internal classes
    }
    public static void main(String[] args) {
        Outer outer=new Outer();
        outer.print();//Calling methods of external classes
    }
}

Operating screenshots:

Explain that in the above code, new Inner().print(); the code corresponds to
Inner inner=new Inner();
Inner.print();

 

II. Static Internal Classes

1. An internal class is called a static internal class if it uses a static declaration. (Actually, it's also equivalent to an external class) can be accessed through an external class. an internal class.

2. The use of static internal classes: internal classes do not need instances of external classes (pay attention to distinguishing member internal classes). Static internal classes exist only to provide services for external classes or logically belong to external classes, and logically can exist independently.

3. The characteristics of static inner classes:

Static internal classes do not hold references to external classes

Static internal classes can access external static variables, if accessing member variables of external classes must be accessed through instances of external classes.

4. Only internal classes in Java can be static

Use format: Outer.Inner = new Outer.Inner();

Code demonstration 1:

/*
 * Static interior
 */
public class Company {
    String companyNam;
    static String country;
    static class Clear{
        String name;
        public Clear() {
            // TODO Auto-generated constructor stub
        }
        
        public Clear(String name) {
            super();
            this.name = name;
        }

        public void work(String name){
            String na=new Company().companyNam="association";
            country="China";
            System.out.println(name+"by"+na+"Cleaning, the company belongs to"+country);
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Company.Clear zcl=new Company.Clear();
        zcl.work("shen_hua");
    }

}

Operating screenshots:

Code demonstration 2:

/*
 * Static inner class
 */
public class Outer {
    private static String info="Hello World";
    private int i=8;
    
    static class Inner{
        int num=new Outer().i;//Get the non-static member variables of the external class, and the Jingtian member variables can be used directly.
        public  void show() {
            System.out.println(info+"---"+num);
        }
    };
}

public class Test {
    public static void main(String[] args) {
        Outer.Inner inner=new Outer.Inner();
        inner.show();
    }
}

Operating screenshots:

3. Local internal classes:

1. Local inner classes are also called region embedded classes. Local inner classes are similar to member inner classes. However, region embedded classes are embedded classes defined in a method.

2. Use occasions: If an internal class object is used only for a method of an external class, use a local internal class

3. Characteristics:

Used within a method, the scope of action is limited to the method.

Decide to hold external class object references as appropriate

Can't use private, protected, public modifiers

Cannot contain static members

Code demonstration 1:

/*
 * Local inner class
 */
public class School {

    String schoolName;
    String buss="Training talents";
    int studentNum;
    public School() {
        // TODO Auto-generated constructor stub
    }
    
    public School(String schoolName, String buss, int studentNum) {
        super();
        this.schoolName = schoolName;
        this.buss = buss;
        this.studentNum = studentNum;
    }

    //Propaganda
    public void show(){
        final double tvMoney=10000;
        final double netMoney=20000;
        class AdverTeam{
            String teamName="shen_hua";
            //TV publicity
            public void tvShow(){
                System.out.println("The propaganda team is:"+teamName);
                System.out.println("This is the TV publicity, the name of the school."+schoolName+",Business content:"+buss+",Number of schools:"+studentNum+",Advocacy costs"+tvMoney);
            }
            //Network propaganda
            public void netShow(){
                System.out.println("The propaganda team is:"+teamName);
                System.out.println("This is the Internet publicity, the name of the school."+schoolName+",Business content:"+buss+",Number of schools:"+studentNum+",Advocacy costs"+netMoney);
            }
        }
        new AdverTeam().tvShow();
        new AdverTeam().netShow();
    }
}
public class Test {
    public static void main(String[] args) {
        School qinghua=new School("tsinghua","Internet Training",1000);
        
        qinghua.show();
    }
}

Operating screenshots:

IV. Anonymous Internal Classes

1. If an internal class is used only once in the whole operation, it can be defined as an anonymous internal class. Anonymous inner classes are also nameless inner classes, which is a mechanism designed by java to facilitate our programming, because sometimes some inner classes just need to create an object of it, which will not be used in the future. At this time, it is more appropriate to use anonymous inner classes.

2. Use occasion: simplify the use of internal classes

3. Characteristics:

Create with new, no specific location

Create an anonymous class that inherits or implements the type after new by default

Determine whether to hold external class object references based on usage

The. class file generated after compiling the built-in anonymous class is named as "external class name $number. class" and numbered as 1, 2, 3... n, the file numbered x corresponds to the Xth anonymous class

Code demo:

/*
 * Anonymous Inner Class
 */
public interface Person {
    public void run();
}

/*
 * Test class
 */
public class Test {
    public static void main(String[] args) {
        Person p=new Person() {        
            public void run() {
                System.out.println("Anonymous internal class implementations");
            }
        };
        p.run();
    }

}

Operating screenshots:

Posted by skippa on Mon, 22 Apr 2019 12:42:35 -0700