Java基础知识之对.this的疑惑

在看《Think in Java》时看到有讲.this的知识,以前只用过this这个关键字,对于.this很是陌生。

书中是这样写的’如果你需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟原点和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();
    }

}
看到这些代码,我有些疑惑,DotThis.this是直接返回一个DotThis对象吗?和new DotThis()有什么区别?只是这么看,干思考是没多大用,那就实践见分晓。之后我改了代码,改的代码:

package innerclassses;

/**
 * @Auther Dongqiang
 * @Date 2018/1/23 11:23
 */
public class DotThis {

    void f() {
        System.out.println("DotThis.f()!");
    }

    public class Inner {

        public DotThis outer1() {
            return new DotThis();
        }

        public DotThis outer2() {
            return DotThis.this;
        }
    }
    public Inner inner1() {
        return new DotThis.Inner();
    }

    public Inner inner2() {
        return new Inner();
    }

}
package innerclassses;

/**
 * @Auther Dongqiang
 * @Date 2018/1/23 11:30
 */
public class DotThisTest {
    public static void main(String[] args) {
        DotThis dotThis = new DotThis();
        DotThis.Inner inner1 = dotThis.inner1();
        DotThis.Inner inner2 = dotThis.inner2();

        System.out.println(inner1.equals(inner2));//false

        System.out.println(dotThis.equals(inner1.outer1()));//false
        System.out.println(dotThis.equals(inner1.outer2()));//true

        System.out.println(dotThis.equals(inner2.outer1()));//false
        System.out.println(dotThis.equals(inner2.outer2()));//true
    }
}



结果是outer2()返回的DotThis.this对象和开始创建的doThis是同一个,所以现在我就可以理解书中的那句话”如果你需要生成对外部类对象的引用,可以使用外部类的名字后面紧跟原点和this“,关键在对外部类对象的应用,我们写全了来看dotThis.inner1().outer2()和dotThis,就可以看到DoThis.this就是调用这个方法的对象。可以通过如下的图来理解


也就是外部类生命内部类,而内部类使用声明他的外部类。这就是我的理解,如果有什么不对的地方请留言。谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值