zno2

嵌套类,内部类

 https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

 

public class Outer {

    private int a = 1;

    Outer() {
        System.out.println("Outer()");
        System.out.println(Outer.this.a);
    }

    private class Inner {
        private int b = 2;

        Inner() {
            System.out.println("Inner()");
            System.out.println(Outer.this.a);
            System.out.println(Inner.this.b);
        }

        private class Innner {
            private int c = 3;

            Innner() {
                System.out.println("Innner()");
                System.out.println(Outer.this.a);
                System.out.println(Inner.this.b);
                System.out.println(Innner.this.c);
            }
        }
    }

    public static void main(String[] args) {
        new Outer().new Inner().new Innner();
    }

}

 

结果:

Outer()
1
Inner()
1
2
Innner()
1
2
3

 

this

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

 

Within an instance method or a constructor, this is a reference to the current object —— the object whose method or constructor is being called.

在当前类中 this 等价于 当前类名.this

public class Outer {

    Outer() {
        System.out.println(Outer.this.equals(this));
    }

}

打印结果是 true

这个全限定名 Outer.this 或者 x.y.Outer.this 用于内部类中引用外部类

没有内部类的时候通常简写 this

 

非静态内部类,必须调用构造函数才可以使用内部成员变量,方法和内部类。

 

内部类可简单看做普通方法,静态的直接用,非静态的调用构造函数用(比普通函数多了一个new)

 

非静态内部类

new Outer().new Inner();

静态内部类

new Outer.Inner();

posted on 2023-06-01 17:07  zno2  阅读(12)  评论(0编辑  收藏  举报

导航