java中,使用this的地方,完全可以不使用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();
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
内部类需要引用外部类的实例对象
局部变量和全局变量名称重复,需要用
this指定引用的是全局变量建造者模式的
return this应该也算吧构造函数调用其它重载构造函数
你说的这些都是不应当使用
this地方,但是在构造方法里调用自身其他构造方法,你能不使用this吗?this好像目前最常用的就是匿名类了。其实我倒是觉得
this很多情况下只是标识作用了,比如区分一下this.name跟super.name一个是自己的,一个是父类的。仅仅是为了代码可读还有在内部类的时候也必须用到
this。只要没有歧义就可以不用this。
static方法里面不能用this,是因为static方法里面没有自己这个实例。
或者
另外还有个常见的this不对的情况
this是用来解析依附于实例的符号的,比如字段名,方法名。在变量名有歧义的时候添加。
关于this的实现可以看看我的这篇博客Java方法调用,应该会对你有帮助。