关于this 的使用

 

如有不对的地方请大家指出,呵呵.

 

 this 的使用

1. this是指当前对象自己。
当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中:
public class A
{
 String s = "Hello";
 public A(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)
 {
  new A("HelloWorld!");
 }
}

运行结果:
   s = HelloWorld!
   1 -> this.s = Hello
          2 -> this.s = HelloWorld!
在这个例子中,构造函数A中,参数s与类A的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类A的变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对参数s进行打印结果;后面两行分别是对对象A的变量s进行操作前后的打印结果。

2. 把this作为参数传递
当你要把自己作为参数传递给别的对象时,也可以用this。如:
public class A
{
 public A()
  {
   new B(this).print();
  }
 public void print()
  {
   System.out.println("Hello from A!");
  }
}
public class B
{
 A a;
 public B(A a)
  {
   this.a = a;
  }
 public void print()
  {
   a.print();
   System.out.println("Hello from B!");
  }
}
运行结果:
Hello from A!
Hello from B!
在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。

3. 注意匿名类和内部类中的中的this。
有时候,我们会用到一些内部类和匿名类。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如下面这个例子:
public class A {
int i = 1;
public A() {
Thread thread = new Thread() {
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();
}
}
在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run

 

QQQQQQQQQQQQQQQ
我在同一个类中定义了好几个构造方法并且想在一个构造方法中调用另一个。
答:在构造方法第一行调用this(...)。
例子:

public class Q1
{
 static int ww;
 static String name;
 public Q1(int i,String n)
 {
  name=n;
  ww=i;
  System.out.println(i);
 }
 Q1()
 {
  this(ww,name);
  System.out.println(ww);
 }
 void add()
 {
  System.out.println("1254");
 }
 public static void main(String [] args)
 {
  Q1 q=new Q1();
  
 // System.out.println("fdfd");
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值