当前位置: java基础教程 > 07-面向对象 > 阅读正文

this 关键字

2021.2.18.   520 次   541字

this 关键字有 3 种作用

1.表示成员变量和成员方法

语法格式为

this.变量名;  //(或方法名)

例如,把局部变量的 name 赋值给 成员变量的 name

public class Person {
	private String name; //成员变量的 name
	public void setName(String name) {  //局部变量的 name
		this.name = name;
	}
}

当成员变量(或方法) 和 局部变量(或方法) 重名时,用 this.变量名 表示成员变量

2.调用其他构造方法

语法格式为

this(参数);

例如,在 person 类的空参构造中,调用其他构造

public class Person {
	private String name;
	public Person() {
		this("zhangsan");
 //在空参构造里,调用其他构造
	}
	public Person(String name) {
		this.name = name;
	}
}

( this调用构造方法,必须在构造方法的第一行,且不能与 super() 同用)

3.用作返回值

语法格式为

return this;

this 的值,绑定的是当前调用它的类,谁调用它,this 就绑定谁

public class Person {
	public Person returnMyself() {
		return this;
	}
}

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群