Thinking in java 之:this关键字

this关键字:

this关键字只能在方法内部使用,指“调用方法的那个对象”的引用,this的用法和其他对象引用并无不同,但要注意,如果在方法内部调用同一个类的另一个方法,就不必使用this,直接调用即可。例如:

public class Dog {

	public void eat(){
		drink();
	}
	public void drink(){
		
	}
}
在eat()内部,你可以写成this.drink();但无此必要,编译器会帮你自动添加。只有当需要明确指定对当前对象引用的时,才需要用到this关键字。

例如:在实体类中通过get,set方法的获取属性值的时候。

this关键字对于将当前对象传递给其他方法也很有用。例如:

class Person {
	public void eat(Apple apple){
		Apple peeledapple=apple.getPeeled();
		System.out.println("nice");
	}
}

class Peeler{
	//给苹果去皮
	static Apple getPeeled(Apple apple){
		return apple;
	}
}

class Apple{
	Apple getPeeled(){
		return Peeler.getPeeled(this);
	}
}

public class PassingThis{
	public static void main(String[] args) {
		new Person().eat(new Apple());
	}
}
这里苹果将通过this关键字将自身传递给了外部方法。

通过this在构造器中调用构造器:

class Demo {

	public Demo() {			}
	public Demo(String s) {
		 System.out.println("ss");
	}
	 
	public Demo(int i){
		 this();
		 System.out.println(1111); //构造器必须放在最前面,否则编译报错	 
		 this("ss");	//编译报错,can't call two
		 this();	//编译报错,Constructor call must be the first statement in a constructor
	}
	 
	void Ways(){
		 this("ss"); 	//编译报错,
	}
	 
	public static void main(String[] args) {		}	
}

上面的例子表明:

1.尽管可以用this调用一个构造器,但却不能在一个构造器中同时调用2个。

2.必须将构造器调用置于最起始处(也就是构造方法中的最前面),否则编译出错。

3.Ways()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造器。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值