为爱奔跑


无论在家出家。必须上敬下和。忍人所不能忍。行人所不能行。代人之劳。成人之美。静坐长思己过。闲谈不论人非。行住坐卧。穿衣吃饭。从幕至朝。一名佛号。不令间断。或小声念。或默念。除念佛外。不起别念。若或妄念一起。当下就要教他消灭。当生惭愧心及忏悔心。从有修持。总觉我工夫很浅。不自矜夸。只管自家。不管人家。只看好样子。不看坏样子。看一切人都是菩萨。唯我一人是凡夫!

  在团队代码中看到对于当前类中的方法,使用了this关键字。经过测试发现,在此种情况下,this关键字的使用可有可无。因此,对java中this的使用做下总结:

package testTHIS;

public class TestTHIS {

    int flag = 0;

    public static void main(String[] args) {
        Test test = new Test();
        test.main();

        TestTHIS tt = new TestTHIS();
        tt.say(); // 不能使用this.say();
    }

    public void say() {
        MyTest mt = new MyTest();
        mt.main();
        int i = this.flag;
        int k = flag;
    }
}

class Test {

    public void main() {
        say1();
        this.say1();
        say2();
        this.say2();
        say3();
        this.say3();
        say4();
        this.say4();
    }

    public void say1() {
        System.out.println("111111111111111");
    }

    protected void say2() {
        System.out.println("222222222222222");
    }

    void say3() {
        System.out.println("333333333333333");
    }

    private void say4() {
        System.out.println("444444444444444");
    }
}

class MyTest extends Test {

    @Override
    public void main() {
        this.say1();
    }
}
Java中不推荐使用this关键字的情况

  对于两种情况,必须使用关键字this。构造方法中和内部类调用外部类当中的方法,demo如下:

public class Test {
    private final int number;

    public Test(int number){
        this.number = number; // 输出5
        // number = number; 输出0
    }

    public static void main(String[] args) {
        Test ts = new Test(5);
        System.out.println(ts.number);
    }
}

  上面的示例代码展示了构造方法中使用this的情况,如果不使用会出错。此外我们可以查看JDK的源码,如String类中的多种构造方法,都使用了this关键字。此外,我倒是觉得this很多情况下只是标识作用了,比如区分一下this.name 跟 super.name 一个是自己的,一个是父类的。仅仅是为了代码可读。

public class A {
    int i = 1;
    public A(){
        // thread是匿名类对象,它的run方法中用到了外部类的run方法
        // 这时由于函数同名,直接调用就不行了
        // 解决办法: 外部类的类名加上this引用来说明要调用的是外部类的方法run
        // 在该类的有事件监听或者其他方法的内部若要调用该类的引用,用this就会出错,这时可以使用类名.this,就ok了
        Thread thread = new Thread() {

            @Override
            public void run() {
                for (;;) {
                    A.this.run();
                    try {
                        sleep(1000);
                    } catch (InterruptedException ie) {
                    }
                }
            }
        };
        thread.start();
    }

    public void run() {
        System.out.println("i = " + i);
        i++;
    }

    public static void main(String[] args) throws Exception {
        new A();
    }
}

  上述展示了匿名内部类中使用关键字this的用法,当内部类中的方法和外部类中的方法同名的时候,如果想在内部类中使用外部类中的同名方法,要用外部类.this.方法类,来显示的使用外部类中的同名方法。

posted on 2016-08-29 11:30  RunforLove  阅读(717)  评论(0编辑  收藏  举报