Java中this语句

this使用原文

自己的理解加修改

1.指当前对象自己

可以区分对象中的成员变量及传进来的参数。比如在对象的成员名称与参数名字相同时,如果直接使用变量名的话,会被编译器认为是对传进来的参数进行操作,但是加上this后就可以对对象的成员变量进行操作了。Eg:

public class Hello { 

    String s = "Hello"; 

    public Hello(String s){ 
        System.out.println("s = " + s); 
        System.out.println("1 -> this.s = " + this.s); 
        this.s = s; 
        System.out.println("2 -> this.s = " + this.s); 
    } 

    public static void main(String[] args) { 
    Hello x=new Hello("HelloWorld!"); 
    } 
}
运行结果:s = HelloWorld! 		这里s为传进去的参数
1 -> this.s = Hello 	这个即为Hello的成员变量s
2 -> this.s = HelloWorld!		这里s是将参数传给成员变量Hello.s

2.把this作为参数传递

即是说调用当前对象的方法,而不是外部的对象的方法,这里强调的是使用的是当前操作的对象的方法。
Eg:

class A { 
	  public A() { 
	    new B(this).print(); 	//此处this是把A类对象作为参数传给B中方法B,其即为B(A)
	  } 

	  public void print() { 
	    System.out.println("Hello from A!"); 
	  }
	} 
	//B对象
class B { 
	  A a; 
	  public B(A a) { 
	    this.a = a; 	//将形参a传给B.a
	  } 
		//B对象的方法
	  public void print() { 
	    a.print(); 
	    System.out.println("Hello from B!"); 
	  } 
	} 
public class This {
		public static void main(String []args)
		{
		   new B(new A());
		}
	}
运行结果: 
Hello from A!   A.print()的结果
Hello from B! 	B.print()的结果

3.匿名类和内部类中的中的this

用到一些内部类和匿名。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。
Eg:

class A{
	   int i = 1;
	    public A() { 
	        Thread thread = new Thread() { 
	            public void run() { 
	                for(;;) { 
	                    A.this.run(); 	//这里是指创建A类对象的run方法
	                    try { 
	                        sleep(1000); 
	                    } catch(InterruptedException ie) {     }
	
	                } 
	           } 
	        }; //注意这里有; 这里创建的一个对象thread
        thread.start(); 
    } 

    public void run() { 
        System.out.println("i = " + i); 
        i++; 
    } 

}
 
 public class This
 {
	    public static void main(String[] args) throws Exception
	    { 
	        new A(); 
	    }
 }
运行结果:
i = 1   每隔一秒i+1输出.....

4.在构造函数中,通过this可以调用同一class中别的构造函数

Eg:

 class Flower{ 
    Flower (int petals){
    	System.out.print(petals);
    } 
    Flower(String ss){
    	System.out.println(ss);
    } 
    Flower(int petals, String ss){ 
         //petals++;调用另一个构造函数的语句必须在最起始的位置 
         this(petals); 
        //this(ss);会产生错误,因为在一个构造函数中只能调用一个构造函数 
    } 
} 
 public class This
 {
	 public static void main(String []args)
	 {
		 new Flower(3,"hcusdhfuchdhcf");
	 }
 }
运行结果:
3

值得注意的是:
1.在构造调用另一个构造函数,调用动作必须置于最起始的位置。
2.不能在构造函数以外的任何函数内调用构造函数。
3.在一个构造函数内只能调用一个构造函数。

End

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值