java里面that.和this.的
时间: 2023-12-10 10:04:30 浏览: 27
"this" 关键字表示当前对象的引用,可以用于区分类的成员变量和方法参数中的同名变量。例如:
```java
public class Person {
private String name;
public void setName(String name) {
this.name = name; // 使用 this 关键字指代当前对象的 name 成员变量
}
}
```
而 "that" 不是 Java 语言的关键字,通常是程序员自己定义的变量名,用于指代其他对象的引用。例如:
```java
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public boolean equals(Student that) {
return this.name.equals(that.name) && this.age == that.age;
}
}
```
在上面的例子中,equals 方法中的参数 that 就是用来指代另一个 Student 对象的引用。
相关问题
java里面that.跟this.的区别
在Java中,"this"和"that"都是关键字,用于引用对象或类的成员变量、方法和构造函数。它们之间的区别在于:
1. "this"关键字只能在类的内部使用,它指的是当前对象的引用。可以使用它来访问当前对象的属性或调用当前对象的方法。
2. "that"关键字可以在类的内部和外部使用,它指的是其他对象的引用。通常使用它来引用其他对象的属性或方法。
例如,下面的代码演示了"this"关键字的用法:
```
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name; // 使用this关键字访问当前对象的属性
this.age = age;
}
public void introduce() {
System.out.println("My name is " + this.name + ", and I'm " + this.age + " years old."); // 使用this关键字调用当前对象的方法
}
}
```
而下面的代码演示了"that"关键字的用法:
```
public class Main {
public static void main(String[] args) {
Person p1 = new Person("Tom", 18);
Person p2 = new Person("Jack", 20);
System.out.println(p1.name); // 直接访问对象的属性
System.out.println(p2.getName()); // 使用对象的方法访问属性
System.out.println(that.name); // 错误!无法访问“that”关键字
}
}
```
java里面this.和that.的区别
在Java中,this和that都是用来引用对象的关键字,但它们有不同的含义和用法。
this关键字用于引用当前对象的实例,通常用于以下情况:
1. 解决变量名冲突:当局部变量和实例变量同名时,使用this关键字可以明确指定使用实例变量。
2. 在一个构造函数中调用另一个构造函数:使用this关键字可以调用该类中的其他构造函数。
3. 在实例方法中返回当前对象的引用:使用this关键字可以返回当前对象的引用。
that关键字在Java中并不存在,也不是任何关键字的别名。您可能在某些情况下看到使用“that”来引用对象,但这只是一种编码风格的选择,通常与“this”关键字一起使用,以增加代码可读性和清晰度。