java中关键字this的使用
2016-08-29 11:30
302 查看
在团队代码中看到对于当前类中的方法,使用了this关键字。经过测试发现,在此种情况下,this关键字的使用可有可无。因此,对java中this的使用做下总结:
Java中不推荐使用this关键字的情况
对于两种情况,必须使用关键字this。构造方法中和内部类调用外部类当中的方法,demo如下:
上面的示例代码展示了构造方法中使用this的情况,如果不使用会出错。此外我们可以查看JDK的源码,如String类中的多种构造方法,都使用了this关键字。此外,我倒是觉得
上述展示了匿名内部类中使用关键字this的用法,当内部类中的方法和外部类中的方法同名的时候,如果想在内部类中使用外部类中的同名方法,要用外部类.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.方法类,来显示的使用外部类中的同名方法。
相关文章推荐
- Java关键字this、super使用总结(转)
- Java关键字final、static、this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- this关键字的使用(摘录Thinking In Java)
- Java关键字this、super使用总结
- java--关键字this、super使用总结
- Java入门每日小练(二)之this关键字的使用
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- java笔记 chapter3使用java类,关键字new,this,变量初始化,引用传递
- JAVA this关键字的使用
- Java关键字final、static、this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- Java关键字this、super使用总结
- java中this和super关键字使用详解
- Java关键字this、super使用总结
- Java 关键字super和this的使用及区别