Detailed Explanation of the Principle and Usage of java Internal Class

  • 2021-07-26 07:44:41
  • OfStack

In this paper, the principle and usage of java internal classes are described with examples. Share it for your reference, as follows:

Concept

Inner class: A class that can be included in another class

External classes: Classes that contain inner classes

Each inner class will be compiled into a separate class, generating a separate bytecode file.

The inner class can easily access the private variables of the outer class, and the inner class can also be declared as private to completely hide from the outside.

Classification

Four inner classes in java (divided according to where and how they are defined)

-Static inner classes -Member inner class -Method inner class -Anonymous inner classes

Classified introduction

-Static inner classes

Feature: There is another class inside the class, and the class is modified by static

Scope of use: Within an external class, you can use the internal class directly or outside the scope of the external class 外部类名.静态内部类名 Use the inner class in the way of


public class StaticOuter {
    private static int shared = 100;
    public static class StaticInner{
        public void staticInnerMethod() {
            System.out.println("Static Inner Method" + shared);
        }
    }
    StaticInner si1 = new StaticInner();
    public void test() {
        StaticInner si = new StaticInner();
        si.staticInnerMethod();
    }
    public static void main(String[] args) {
        StaticOuter so = new StaticOuter();
        so.test();
    // Within the scope of external classes 
        StaticInner si1 = new StaticInner();
        si1.staticInnerMethod();
    // Legal 
    StaticOuter.StaticInner si2 = new StaticOuter.StaticInner();
        si2.staticInnerMethod();
    }
}
// Outside the scope of an external class 
class Test{
    StaticOuter.StaticInner si2 = new StaticOuter.StaticInner();
}

Access scope

Static inner classes can only access static variables and methods in outer classes. Static inner classes can also access private variables in outer classes. Static variables and static methods can be defined in static inner classes.

-Member inner class

Syntax: A member inner class exists as a member of an outer class

Usage:

How to create a new instance of an internal class: You can't use an external class directly. In the way of an internal class, each member internal class object corresponds to an external class instance, so you need to create an external class instance first before you can generate an internal class instance (such as the following code)

Access scope:

Member inner classes can access static variables and methods in outer classes, as well as instance variables and methods. But there are two writing formats:

(1) Direct access;

(2) 外部类.this.xxx Mainly for external classes and internal classes have the same variable name or method name.

Member inner classes can also access private variables of outer classes

Static variables and static methods cannot be defined in internal classes of members (with the exception of final variables, which are equivalent to constants), There can be no static variables and methods in the following method inner classes and anonymous inner classes, because static variables and static methods are generally used independently as attributes and methods of types, while member inner classes are associated with one external class instance to one, so they are not used independently, so this use is of little significance. This is a rule.


public class OriginalClass {
    private static int t1 = 100;
    private int t2 = 200;
    class OriginalInner{
        public void test() {
      /*
           *  Illegal representation, static variables and methods cannot be defined in members' internal classes 
          public static int inner = 100;
          public static void print() {
          }
          */
          // Legal final Variable 
          public static final int inner1 = 300;
            System.out.println("OriginalInner:"+ t1);// Direct access to external class static variables 
            System.out.println("OriginalInner:"+ t2);// Direct access to external class member variables 
            action();// Direct access to external class methods 
            System.out.println("OriginalInner:"+ OriginalClass.this.t1);//
            System.out.println("OriginalInner:"+ OriginalClass.this.t2);
            OriginalClass.this.action();
        }
    }
    public void action() {
        System.out.println("originalinner action");
    }
    public static void main(String[] args) {
    //new1 Inner classes 
        OriginalClass oc = new OriginalClass();
        OriginalInner oi = oc.new OriginalInner();
        oi.test();
    }
}

-Method inner class

Syntax: Classes that exist inside the method body

Scope of use: Method inner classes can only be used within defined methods

Access scope:

If the method containing the inner class is an instance method, you can access the static variables and methods of the outer class as well as the instance variables and methods;

If the method containing the inner class is static, you can only access the static variables and methods of the outer class.

Method inner classes can also directly access the parameters of the method and local variables in the method, but these variables must be declared as final. Why should it be declared final? This is because the internal class of the method does not operate on external variables, but its own instance variables, but the values of these variables are the same as those of the external ones. Assigning values to these variables will not change the external values. To avoid confusion, it is simply mandatory to declare them as final.

We know that the values of basic type variables modified by final cannot be modified, and the references of arrays or reference type variables modified by final cannot be modified, that is, they can only point to 1 object or array, but we can modify the values of member variables in objects or elements in arrays.

In fact, the purpose of using final to modify parameters and local variables is to ensure that elements outside the method inner class will not be modified in the method inner class, which is equivalent to limiting the function of one scope, and to ensure that the modification inside the method inner class will not affect the value of variables with the same name outside the method inner class.


public class FunctionOuter {
    private static int s= 100;
    private int s1 = 20;
    public void print(final int param) {
        final int in = 300;
        class FunctionInner{
            public void innertest() {
                System.out.println("FunctionInner : s="+s);
                System.out.println("FunctionInner : s1="+s1);
                System.out.println("FunctionInner : in"+ in);
                test();
            }
        }
        FunctionInner fi = new FunctionInner();
        fi.innertest();
        System.out.println("print:in"+in);
    }
    public void test() {
        System.out.println("FunctionOuter : "+s);
    }
    public static void main(String[] args) {
        FunctionOuter fo = new FunctionOuter();
        fo.print(900);
    }
}

-Anonymous inner classes

Syntax: An anonymous inner class does not have a separate class definition, which defines the class at the same time as the object is created


new  Parent class ( Parameter list ){
  // Anonymous inner class implementation part 
}


new  Parent interface (){
  // Anonymous inner class implementation part 
}

Anonymous inner classes can only be used once to create 1 object. There is no name, no constructor, but the parent constructor can be called based on the argument list.

You can define instance variables and methods in anonymous inner classes, As well as initialization code block, initialization code block can play the role of constructor, but there can be multiple constructors, but initialization code block can only have one block, because there is no constructor, it cannot accept parameters by itself, and if parameters are necessary, other internal classes should be used.

An anonymous inner class can access all variables and methods of an outer class, and can access final parameters and local variables in methods

More readers interested in java can check the topics of this site: "Introduction and Advanced Tutorial of Java Object-Oriented Programming", "Tutorial of Java Data Structure and Algorithm", "Summary of Java Operating DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"

I hope this article is helpful to everyone's java programming.


Related articles: