类名.This用法

类名<spanlang=EN-US>this一般是用在内部类中,用来表示当前实例。

根据例子来看<spanlang=EN-US>

Main.java

 

/**

 * Created with IntelliJ IDEA.

 * User: Erica

 * Date: 13-9-24

 * Time: 上午10:44

 * 查看类名.this有什么作用

 */

public class Main {

    static int id;
    public static void main(String[] args) {

        new Main().test();
    }

    public void test() {

        ThisDemo2 thisDemo = new ThisDemo2();
        thisDemo.test();

    }
 //内部类
    class ThisDemo2 {
        public ThisDemo2() {

            id++;

        }

 

        /**

         * 打印出内部类以及外部类

         */

        public void test() {

            System.out.println("内部类.this = "+ThisDemo2.this + ":" + id);

            System.out.println(" this = "+this + ":" + id);

            System.out.println("外部类.this = "+Main.this);

        }
    }
}
output:
内部类.this = Main$ThisDemo2@69b332:1

 this = Main$ThisDemo2@69b332:1

外部类.this = Main@173a10f

可以看出在內部類中<spanlang=EN-US>this指向的是內部類的當前實例,如果想訪問外部類的當前實例時,可以通過外部類名.this實現<spanlang=EN-US>



posted on 2013-09-24 14:22  西顾  阅读(314)  评论(0)    收藏  举报