【Java笔记】Java 中 this 用法小结

据我所知,this有三个用途,但this都表示当前对象自身。

 

一、访问当前对象的数据域

 

public class TestThis {
	
	public int age;
	
	public TestThis() {
		age = 1;
	}
	
	public TestThis(int age) {
		this.age = age;
	}
} 
 
 
 
 
 

当构造方法传入的变量的变量名和当前对象数据域中的变量名一样时,可以使用 this 来访问当前对象数据域的变量。

 

二、调用当前对象的构造方法

 

public class TestThis {
	
	public int age;
	public String name;
	public char sex;
	
	public TestThis() {
		sex = 'm';
	}
	
	public TestThis(String name) {
		this();
		this.name = name;
	}
	
	public TestThis(int age) {
		this();
		this.age = age;
	}
	
	public TestThis(String name, int age) {
		this(name);
		this.age = age;
	}

	public static void main(String[] args) {
		TestThis testThis = new TestThis("PIGGY", 18);
		System.out.println("name:" + testThis.name + "\nage:" + testThis.age + 
				"\nsex:" + testThis.sex);
	}

}

 

输出结果为:

 

name:PIGGY
age:18
sex:m

 

这个用法需要注意:

(1)在一个构造方法中可以使用 this(); 来调用另一个构造方法,但不可以调用两个。

(2)必须将构造方法的调用放在方法的起始位置,不然会报错。

 

三、返回当前对象自身

 

public class TestThis {
	
	public int number;
	
	public TestThis() {
		number = 0;
	}
	
	TestThis returnSelf() {
		number++;
		return this;
	}
	
	public static void main(String[] args) {
		TestThis testThis = new TestThis();
		System.out.println("返回次数:" + testThis.returnSelf().returnSelf().returnSelf().number);
	}

}

 

输入结果为:

 

返回次数:3

 

这里的 this 放回的是当前对象本身,所以 testThis.returnSelf() 是个 TestThis 对象,它也有自己的 number 变量和 returnSelf() 方法,以此类推 testThis.returnSelf().returnSelf().returnSelf() 也是一个 TestThis 对象,它也有自己的 number 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值