java中this的用法

1. 当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)

public class A {
//成员变量
private int size;

public void test(int size) {
//将局部变量size赋给成员变量this.size
this.size = size;
}

}

2.把自己当作参数传递时,也可以用this.(this作当前参数进行传递)


public class B {
private C c;

public B(C c) {
this.c = c;
}

public void print() {
//调用C的print方法
c.print();

System.out.println("B!");

}

public static void main(String args[])
{
C c = new C();
c.print();
B b = new B(c);
b.print();

}
}

class C
{
public C() {
//调用B的print方法
new B(this).print();

}

public void print() {

System.out.println("C!");

}
}

在这个例子中,对象C的构造函数中,用new B(this)把对象C自己作为参数传递给了对象B的构造函数。

3. 有时候,我们会用到一些内部类和匿名类,如事件处理。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。


public class E {

int i = 1;

public E() {

Thread thread = new Thread() {

public void run() {

for (int j = 0; j < 20; j++) {

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

}

}


在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run。

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

public class F {
/**
* 构造函数1
* @param x
*/
F(int x) {

}
/**
* 构造函数2
* @param y
*/
F(String y)
{

}
/**
* 构造函数3
* @param x
* @param y
*/
F(int x,String y)
{
//下面这段代码不能使用,调用另一个构造函数的语句必须在最起始的位置
/*x++;*/
this(x);
//下面这段代码不能使用,同样是因为调用另一个构造函数的语句必须在最起始的位置
/*this(y);*/
}

}


值得注意的是:

  1:在构造调用另一个构造函数,调用动作必须置于最起始的位置。

  2:不能在构造函数以外的任何函数内调用构造函数。

  3:在一个构造函数内只能调用一个构造函数。

5.使用this同时传递多个参数。

public class G {

int x;

int y;

static void showtest(G g) {// 实例化对象

System.out.println(g.x + " " + g.y);

}

void seeit() {

showtest(this);

}

public static void main(String[] args) {

G g = new G();

g.x = 9;

g.y = 10;

g.seeit();

}

}


代码中的showtest(this),这里的this就是把当前实例化的p传给了showtest()方法,从而就运行了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值