java中this关键字的使用
时间: 2023-08-31 14:05:08 浏览: 32
在Java中,this是一个关键字,用于指代当前对象。下面是this关键字的几种使用方式:
1. 表示当前类的成员变量或方法,例如:
```
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name; // 使用 this 关键字表示当前对象的 name 成员变量
this.age = age; // 使用 this 关键字表示当前对象的 age 成员变量
}
public void setName(String name) {
this.name = name; // 使用 this 关键字表示当前对象的 name 成员变量
}
public void setAge(int age) {
this.age = age; // 使用 this 关键字表示当前对象的 age 成员变量
}
}
```
2. 用于调用当前类的构造函数,例如:
```
public class Person {
private String name;
private int age;
public Person() {
this("Tom", 18); // 调用当前类的有参构造函数
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
```
3. 将当前对象作为参数传递给另一个方法,例如:
```
public class Person {
private String name;
private int age;
public void setNameAndAge(String name, int age) {
setName(this.name);
setAge(this.age);
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
```
这里,setNameAndAge方法将当前对象作为参数传递给setName和setAge方法,以设置name和age成员变量。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)