java中关键字this的使用

  在团队代码中看到对于当前类中的方法,使用了this关键字。通过测试发现,在此种状况下,this关键字的使用无关紧要。所以,对java中this的使用作下总结:java

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以下:ide

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.方法类,来显示的使用外部类中的同名方法。测试

相关文章
相关标签/搜索