Java inner class and explain the principles of integration

A consolidation: internal custom Java classes, how to create inner classes, inner classes of classification, relationships within the class and outside the class

Basic concepts within the class

1.1 class definition of internal

Internal categories: so-called internal type operation is nested within the other classes of a class structure.

class Outer{
    private String str ="外部类中的字符串";
    //************************** 
    //定义一个内部类
    class Inner{
        private String inStr= "内部类中的字符串";
        //定义一个普通方法
        public void print(){
            //调用外部类的str属性
            System.out.println(str);
        }
    }
    //************************** 
    //在外部类中定义一个方法,该方法负责产生内部类对象并调用print()方法
    public void fun(){
        //内部类对象
        Inner in = new Inner();
        //内部类对象提供的print
        in.print();
    }
}
public class Test{
    public static void main(String[] args)
    {
        //创建外部类对象
        Outer out = new Outer();
        //外部类方法
        out.fun();
    }
}

The result: the outer string class
but if removed inner class:

class Outer{
    private String outStr ="Outer中的字符串";
    public String getOutStr()
    {
        return outStr;
    }
    public void fun(){  //2
        //this表示当前对象
        Inner in = new Inner(this); //3
        in.print();                 //5
    }
}
class Inner{
    private String inStr= "Inner中的字符串";
    private Outer out;
    //构造注入
    public Inner(Outer out)  //3
    {
        this.out=out;       //4.为Inner中的out变量初始化
    }
    public void print(){    //6
        System.out.println(out.getOutStr()); //7
    }
} 
public class Test{
    public static void main(String[] args)
    {
        Outer out = new Outer();  //1.
        out.fun(); //2.
    }
}

The results: The Outer string
, but after removing the interior class discovery procedure more difficult to understand.

1.2 disadvantages inner class

Inner class advantages:

Internal and external type class can easily access each other's private domain (including private methods, private property).
Another class is an internal packaging, other types of external hidden.
Internal limitations of single inheritance class can implement the java.

Inner class disadvantages:

complex structure.
Record: Use internal class implements multiple inheritance:

class A {
    private String name = "A类的私有域";
    public String getName() {
        return name;
    }
}
class B {
    private int age = 20;
    public int getAge() {
        return age;
    }
}
class Outter {
    private class InnerClassA extends A {
        public String name() {
            return super.getName();
    }
}
    private class InnerClassB extends B {
        public int age() {
            return super.getAge();
    }
}
    public String name() {
        return new InnerClassA().name();
    }
    public int age() {
        return new InnerClassB().age();
    }
}
public class Test2 {
        public static void main(String[] args) {
            Outter outter = new Outter();
            System.out.println(outter.name());
            System.out.println(outter.age());
        }
}

Here Insert Picture Description

2. Create an inner class

2.1 Create a non-static inner classes outside the outer class

Syntax: External Internal class object classes within a class outer class = new () .new inner class ();
for example: Outer.Inner in = new Outer () new Inner ();.

2.2 Creating static inner classes outside the outer class

Syntax: External Internal class object classes within a class outer class = new internal class ();
for example: Outer.Inner in = new Outer.Inner () ;

2.3 Creating inner class syntax inside the outer class

Create inner classes inside the outer class, just as ordinary objects created directly: Inner in = new Inner ();

3. Classification inner class

In Java inner class are divided into members of inner classes, static inner classes, methods, inner classes, anonymous inner classes

3.1 members of the inner class

Analogy member method

  1. Internal members of the inner class does not allow the presence of any static variable or method, as members of the method can not have any static properties (members of the methods associated with the object, static properties and class-related)
class Outer {
    private String name = "test";
    public  static int age =20;

    class Inner{
        public static int num =10;
        public void fun()
        {
            System.out.println(name);
            System.out.println(age);
        }
    }
}
public class Test{
    public static void main(String [] args)
    {}
}

Here Insert Picture Description
2. The members of the inner class is attached to the outer class, only to create an external class can create inner classes.

3.2 static inner classes

Keywords can be modified static member variables, methods, code blocks, in fact, can also be modified inner classes, using a modified static inner class we call static inner classes, there is a difference between the maximum internal static and non-static inner classes, non-static inner classes after compilation will be completed implied holds a reference that points to the enclosing class that created it, but there is no static class. Without this quote means:
  Creating 1. static inner classes do not need to rely on external class can be created directly.
  2. static inner classes can not use any non-static class outside the class (including properties and methods), but may have its own member variables.

class Outer {
    public String name = "test";
    private static int age =20;

    static class Inner{
        private String name;
        public void fun()
        {
            System.out.println(name);
            System.out.println(age);
        }
    }
}
public class Test{
    public static void main(String [] args)
    {
        Outer.Inner in = new Outer.Inner();
    }
}

Here Insert Picture Description

3.3 Method inner class

The method of the inner class name suggests is defined in the method in the class

  1. Methods inner classes are not allowed access modifier (public, private, protected) are not allowed.
class Outer{
    private int num =5;
    public void dispaly(final int temp)
    {
        //方法内部类即嵌套在方法里面
        public class Inner{
        }
    }
}
public class Test{
    public static void main(String[] args)
    {}
}

Here Insert Picture Description
2. The process of internal to external class completely hidden, except that this method creates a class can access it elsewhere can not be accessed (in other words other methods or classes are not aware of the existence of this class) class method internal to external completely hidden , create a method of this class you can access it elsewhere are not accessible.
3. The method if you want to use internal category parameter, the parameter must be declared final (JDK8 final parameter becomes implicitly stated)

class Outer{
    private int num =5;
    //普通方法
    public void dispaly(int temp)
    {
        //方法内部类即嵌套在方法里面
        class Inner{
            public void fun()
            {
                System.out.println(num);
                temp++;
                System.out.println(temp);
            }
        }
        //方法内部类在方法里面创建
        new Inner().fun();
    }
}
public class Test{
    public static void main(String[] args)
    {
        Outer out = new Outer();
        out.dispaly(2);
    }
}

Here Insert Picture Description

3.4 anonymous inner classes

Anonymous inner class method is a no name inside the class , so the characteristics and methods consistent with the methods inside the class, in addition, also has its own characteristics:
1. anonymous inner class must inherit an abstract class or implement an interface.
2. anonymous inner class has no class name, so there is no constructor.

//匿名内部类
//声明一个接口
interface MyInterface {
    //接口中方法没有方法体
    void test();
}
class Outer{
    private int num = 5;
    public void dispaly(int temp)
    {
        //匿名内部类,匿名的实现了MyInterface接口
        //隐藏的class声明
        new MyInterface()
        {
            public void test()
            {
                System.out.println("匿名实现MyInterface接口");
                System.out.println(temp);
            }
        }.test();
    }
}
public class Test{
    public static void main(String[] args)
    {
        Outer out = new Outer();
        out.dispaly(3);
    }
}

Here Insert Picture Description

4. Relationship between the internal and the external class class

  • For non-static inner class, create inner class instance object depend on outside class, in the absence of external class instance can not be created inside the class.
  • Inner class can access external elements like direct will be the object outside the class passed before an external class to create an inner class, create inner classes - (including the private domain)
class Outer{
    //成员变量  与对象有关
    private String msg;
    private int age;
    //--------------------------
    class Inner{
        public void dispaly()
        {
            //此处有一个隐藏的Outer.this
            msg = "test";
            age = 20;
            System.out.println(msg);
            System.out.println(age);
        }
    }
    //--------------------------
    public void test()
    {
        Inner in = new Inner();
        in.dispaly();
    }
}
public class Test{
    public static void main(String[] args)
    {
        Outer out = new Outer();
        out.test();
    }
}

External class can refer to indirect access to the internal elements by class within the class - - To access internal class property, you must first create an internal class object

class Outer{
    public void dispaly()
    {
        //外部类通过创建内部类的对象间接访问内部类元素
        Inner in = new Inner();
        in.dispaly();
    }
    class Inner{
        public void dispaly()
        {
            System.out.println("内部类");
        }
    }
}
public class Test1{
    public static void main(String[] args)
    {
        Outer out = new Outer();
        out.dispaly();
    }
}
  • Internal class is a relatively independent individuals, not related to the external class.

Reference article:
https://blog.csdn.net/zhao_miao/article/details/83245816

Integration of two: Java inner class and its principles

1. Java inner classes in realization

Java inner classes

I believe we have used inner classes many times, do not say it is how to use the.

2. Internal class

1. The members of the inner class

Java inner classes

Note that, when the members of the class have internal and external class member variables of the same name or this method, the default access inside of the case is a member of the class, such as members of the same name to be accessed outside the class, you need to use the following form:

外部类.this.成员变量外部类.this.成员方法

Inner classes are attached to the outer class exists, that is to create objects within the class members, the premise is to create an object of the outer class, to create a way members of the inner class as follows:

new Main().new Inner();

Members of the inner class can have access to private, protected access, public access, the default access permissions. As with private modification, you can only access inside the outer class.

2. Local inner class

Partial inner class is a class defined in the scope of the method, access to it is limited in scope, or a method.

Java inner classes

You can return the local internal class, like this:

Java inner classes

3. Anonymous inner classes

Anonymous inner classes should we usually use the most, such as the following to create a thread:

Java inner classes

Anonymous inner classes at compile time have the system automatically named: Main $ 1

Anonymous inner class is not a class constructor, mostly for other classes inherit or implement the interface and does not require additional methods, but the method of realization of the inheritance or rewrite

4. Static inner classes

Static inner class is defined in another class inside the class, just in front of the class plus the static. Static inner class need not rely on external class, similar to the static member variable.

Java inner classes

You can create as to create the external static class:

Main.Inner mi = new Main Inner();

3. Internal class implements the principle of

内部类为什么能够访问外部类的成员?

定义内部类如下:

Java inner classes

使用javap命令进行反编译。

编译后得到Main.class Main I n n e r . c l a s s Two More Culture Matter anti- Edit Translate M a i n Inner.class两个文件,反编译Main Inner.class文件如下:

Java inner classes

可以看到,内部类其实拥有外部类的一个引用,在构造函数中将外部类的引用传递进来。

匿名内部类为什么只能访问局部的final变量?

其实可以这样想,当方法执行完毕后,局部变量的生命周期就结束了,而局部内部类对象的生命周期可能还没有结束,那么在局部内部类中访问局部变量就不可能了,所以将局部变量改为final,改变其生命周期。

编写代码如下:

Java inner classes

这段代码编译为Main.class Main$1.class两个文件,反编译Main$1.class文件如下:

Java inner classes

可以看到,java将编译时已经确定的值直接复制,进行替换,将无法确定的值放到了内部类的常量池中,并在构造函数中将其从常量池取出到字段中。

可以看出,java将局部变量m直接进行复制,所以其并不是原来的值,若在内部类中将m更改,局部变量的m值不会变,就会出现数据不一致,所以java就将其限制为final,使其不能进行更改,这样数据不一致的问题就解决了。

匿名内部类为什么访问外部类成员字段不用final?

Above that, final key is to solve the problem of inconsistent data, because there are references to internal classes outside of the class, all changes made to the external field in the class of a true reflection of the outer class instance itself, there is no need to use final modification.

Reference article:
https://www.cnblogs.com/hujingnb/p/10181621.html

Published 107 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/belongtocode/article/details/103367931