内部类之.this&&.new

一、.this

  我们都知道this是指当前类中的对象本身,但是在内部类中需要指明外部类时,this不再起作用,那应该怎么做呢?下面,让我们看看:

public class DotThis {
    void f() {
        System.out.println("DotThis.f()");
    }
    
    public class Inner {
        public DotThis outer() {
            return DotThis.this;
            //A plain "this" would be Inner's "this"
        }
    }
    
    public Inner inner() {
        return new Inner();
    }
    
    public static void main(String[] args) {
        DotThis dt = new DotThis();
        Inner dti = dt.inner();
        //DotThis.Inner dti = dt.inner(); can be the same as pre line.
        dti.outer().f();
    }
}

二、.new

  有时你可能想要告知某些对象,去创建其某个内部类的对象。要实现此目的,你必须在new表达式中提供对其他外部类对象的引用,这是需要使用.new语法,就像下面这样:

public class DotNew {
    public class Inner {
        public Inner() {
            System.out.println("DotNew.Inner.Inner()");
        }
    }
    
    public static void main(String[] args) {
        DotNew dn = new DotNew();     //ok
//        Inner dni = new Inner();      //ok
        Inner dni = dn.new Inner();   //ok
        DotNew.Inner dny = dn.new Inner();   //ok
    }
}