this关键字

2015/04/29 00:37
阅读数 74

THIS:

 

public  class TestThis{

     public void  Test(){

}

Public void TestForThis(){

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

}     

     public static void main(String[] args){

TestThis  tt= new TestThis();

tt.TestForThis();

}

}

 

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

public  class TestThis{

     public void  Test(){

}

Public void TestForThis(){

Test();//没有使用this

}     

     public static void main(String[] args){

TestThis  tt= new TestThis();

tt.TestForThis();

}

}

什么时候该使用this呢?

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

public class  TestThis{

public int a;//类的属性a

public void Test(){

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();

}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部