Java this 关键字

本文介绍 Java this 关键字的作用。

总的来说,Java this 关键字有如下三个特征:

1. 表示类中的属性和调用方法;

2. 调用本类中的构造方法;

3. 表示当前对象;

 

下面根据具体代码说明。

 

1. 表示类中的属性和调用方法,代码:

package hello;

class People1{
	private String name;
	private int age;
	
	public People1(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){
		System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge());
	}
}
public class DemoMethod {

	public static void main(String[] args) {
		People1 p = new People1("张三", 30);
		p.tell();
	}

}

在上述代码中,用到了两次 this,分别是

this.name = name;
this.age = age;

System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge());

第一处的 this 表示了类中的属性,第二处的 this 表示了类的调用方法。

 

 2. 调用本类中的调用方法,代码:

package hello;

class People1{
	private String name;
	private int age;
	
	public People1(String name, int age){
		this();
		this.name = name;
		this.age = age;
	}
	
	public People1(){
		System.out.println("无参数的构造方法");
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){
		System.out.println("姓名:"+ this.getName() + " " + "年龄: " + this.getAge());
	}
}
public class DemoMethod {

	public static void main(String[] args) {
		People1 p = new People1("张三", 30);
		p.tell();
	}

}

程序输出:

无参数的构造方法
姓名:张三 年龄: 30

在 People1 中定义了无参数的构造方法,我们可以通过 this() 调用它,需要注意的是,必须要在程序的第一行调用 this()

 

3. 表示当前对象,代码如下:

package hello;

class People1{
	private String name;
	private int age;
	
	public People1(String name, int age){
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){
		System.out.println(this);
	}
}
public class DemoMethod {

	public static void main(String[] args) {
		People1 p = new People1("张三", 30);
		System.out.println(p);
		p.tell();
	}

}

程序输出:

hello.People1@677327b6
hello.People1@677327b6

可以看出程序输出的对象信息都是一致的。

转载于:https://www.cnblogs.com/changzhi/p/6740814.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值