java中的this关键字完全解读

一文详解java中的this关键字

最近在看《java编程思想》感觉解决了很多以前学习Java遇到的疑惑。这里详细探讨一下this关键字的几大使用范畴:(应该也就只有以下几种用法)
首先this关键字只能在非静态方法内部使用。

  1. 调用一个对象的方法时,this生成一个对象的引用,我们可以像对待其他引用一样对待这个引用。
  • 在一个类的方法里调用其他该类中的方法(这里不用我们加this,直接调用方法即可,this已经自动地应用于其上了。
public class Apricot { 
	void pick() {
		/*...*/
	}
	void pit() {
		pick();
	}
}
//当然在pit()方法中,我们也可以使用this.pick(),但是没必要,编译器会为你做的。
  • 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();
	}
}
//输出 i=3
  • this关键字还可以向其他方法传递当前对象:
class Person {
	public void eat(Apple apple) {
		Apple peeled = apple.getPeeled();
		System.out.println("Yummy");
	}
}
public class Peeler {
	static Apple peel(Apple apple) { 
		// ... remove peel
		return apple; // Peeled
	}
}
public class Apple {
	Apple getPeeled() {
		return Peeler.peel(this);
	}
}
public class PassingThis {
	public static void main(String[] args) {
		new Person().eat(new Apple());
	}
}
//输出Yummy
  1. 在一个构造器中,当你给this一个参数列表时,它不再是当前对象引用的意思,而是通过最直接的方式显示地调用匹配参数列表的构造器:(在构造器中调用构造器,在其它方法里不能用this调构造器):
public class Flower {
	int petalCount = 0;
	String s = "initial value";
	Flower(int petals) {
		petalCount = petals;
		System.out.println("Constructor w/ int arg only, petalCount = " + petalCount;
	}
	Flower(String ss) {
		System.out.println("Constructor w/ string arg only, s = " + ss) ;
		s = ss; 
	}
	Flower(String s, int petals) {
		this(petals);
		//- this(s); // Can't call two!
		this.s = s; // Another use of "this"
		System.out.println("String & int args");
	}
	Flower() {
		this("hi", 47);
		System.out.println("no-arg constructor");
	}
	void printPetalCount() {
		//- this(11); // Not inside constructor!不在构造器内,会报错
		System.out.println("petalCount = " + petalCount + " s = " + s);
	}
	public static void main(String[] args) {
		Flower x = new Flower();
		x.printPetalCount();
	}
}
//输出:
/*
Constructor w/ int arg only, petalCount = 47
String & int args
no-arg constructor
petalCount = 47 s = hi
/*

从构造器 Flower(String s, int petals) 可以看出,其中只能通过 this 调用一次构造器。另 外,必须首先调用构造器,否则编译器会报错。这个例子同样展示了 this 的另一个用法。参数列表中的变 量名 s 和成员变量名 s 相同,会引起混淆。你可以通过 this.s 表明你指的是成员变量 s,从而避免重复。 我们经常会在 Java 代码中看到这种用法。在 printPetalCount() 方法中,编译器不允许你在一个构造器之外的方法里调用构造器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值