Think in Java(二) this关键词

  1. this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。
  2. 只要当需要明确指出对当前对象的引用时,才需要使用this关键字。例如,当需要返回对当前对象的引用时,就常常在return语句中这样写:
public class Leaf {
	int i = 0;
	Leaf increment() {
		i++;
		return this;
	}
	void print() {
		System.out.println("i = " + i);
	}
	public static void main(String[] args) {
		Leaf x= new Leaf();
		x.increment().increment().increment().print();
	}
}

由于increment()通过this关键字返回了当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。
另外,this关键字对于将当前对象传递给其他方法也很有用

class Peeler {
	static Apple peel(Apple apple) {
		//... remove peel
		return apple;	//Peeled
	}
}
class Apple {
	Apple getPeeled() { return Peeler.peel(this); }
}
class Person {
	public void eat(Apple apple) {
		Apple peeled = apple.getPeeled();
		System.out.println("oishi");
	}
}
public class PassingThis {
	public static void main(String[] args) {
		new Person().eat(new Apple());
	}
}
  1. 在构造器中调用构造器

有时候想在一个构造器中调用另一个构造器,以避免重复代码。可用this做到

public class Flower {
	int petalCount = 0;
	String s = "initial value";
	Flower(int petal) {
		petalCount = petal;
		print("Constructor with int arg only, petalCount=" + petalCount);
	}
	Flower(String s) {
		print("Contructor with String arg only, s = " + s);
		this.s = s;
	}
	Flower(String s, int petal) {
		this(petal);
		this.s = s;
		print("String & int args");
	}
	Flower() {
		this("hi", 47);
		print("default constructor (no args)");
	}
	void printPetalCount() {
		print("petalCount = " + petalCount + " s = " + s);
	}
	public static void main(String[] args) {
		Flower x = new Flower();
		x.printPetalCount();
	}
	/* Output:
	Constructor with int arg only, petalCount = 47
	String & int args
	default constructor(no args)
	petalCount = 47 s = hi
	*/

说明:1)用this可以调用一个构造器,但不能调用两个。
2)必须将构造器调用置于最起始处,否则编译器会报错
3)除构造器之外,编译器禁止在其他任何方法中调用构造器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值