Thinking in Java & 内部类

静态内部类可以直接创建对象new B.C();
如果内部类不是静态的,那就得这样
B b = new B();
B.C c = b.new C();
//要想直接创建内部类的对象,不能按照想象的方式,去引用外部类的名字B,而必须使用外部类的对象来创建内部类对象,就像上面的程序中所看到的那样.
1) 如果需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟圆点和this:
public class DotThis {
    void f()
    {
        System.out.println("DotThis.f()");
    }
    public class Inner
    {
        public DotThis outer()
        {
            return DotThis.this;
        }
    }
    public Inner inner()
    {
        return new Inner();
    }

    public static void main(String[] args) {

        DotThis dt = new DotThis();
        DotThis.Inner dti = dt.inner();
        dti.outer().f();
    }
}
output:
DotThis.f()
 
在拥有外部类对象之前是不可能创建内部类对象的,这是因为内部类对象会暗暗地连接到创建它的外部类对象上。但是,如果你创建的是嵌套类(静态内部类),那么它就不需要对外部类对象的引用。
 
Thinking in Java  内部类 - darrell - DARRELL的博客
 
Thinking in Java  内部类 - darrell - DARRELL的博客
 

Thinking in Java  内部类 - darrell - DARRELL的博客 

Thinking in Java  内部类 - darrell - DARRELL的博客
局部内部类:
Thinking in Java  内部类 - darrell - DARRELL的博客
 
Thinking in Java  内部类 - darrell - DARRELL的博客
//匿名内部类:
interface Contents
{
    int value();
}
public class Parcel7 {
    public Contents contents()
    {
        return new Contents() {
            private int i = 11;
            @Override
            public int value() {
                return i;
            }
        };
    }
    public static void main(String[] args) {
        
        Parcel7 p = new Parcel7();
        Contents c = p.contents();
}
}

原文地址:https://www.cnblogs.com/xiarongjin/p/8309828.html