this关键字

THIS:

publicclass TestThis{

public void Test(){

}

Public void TestForThis(){

this.Test();//this可以代表任何对象,在一个方法中,它所代表的对象是不确定的,但它的类是确定的,它所代表的对象只能是当前类;只有在这个方法被哪个对象(类的实例)所调用的时候,this才能确定代表了哪个对象。

}

public static void main(String[] args){

TestThistt= new TestThis();

tt.TestForThis();

}

}

Java允许对象一个成语直接调用另一个成员,可以省略this前缀。

publicclass TestThis{

public void Test(){

}

Public void TestForThis(){

Test();//没有使用this

}

public static void main(String[] args){

TestThistt= new TestThis();

tt.TestForThis();

}

}

什么时候该使用this呢?

方法中的局部变量与类中的属性同名时,想使用类中的属性的时候就应该使用this

publicclass TestThis{

public int a;//类的属性a

public voidTest(){

public int a;//局部变量a

this.a = 12;//调用的是类的属性a

System.out.println(“输出局部变量的a”+a);

System.out.println(“输出类的属性a”+this.a);

}

public static void main(String[] args){

TestThis tt=new TestThis();

tt.test();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值