21xrx.com
2025-04-09 21:43:07 Wednesday
文章检索 我的文章 写文章
Java 中 this 关键字的用法详解
2023-06-17 19:30:41 深夜i     10     0
this 关键字可以在构造方法中使用

在 Java 编程语言中,this 关键字代表当前对象。this 关键字可以在构造方法、实例方法、属性和参数中使用。本文将对 Java 中 this 关键字的使用进行详细介绍和总结。

1. 在构造方法中使用 this 关键字

this 关键字可以在构造方法中使用,用于传递对象的引用。例如,在一个类中,有两个构造方法,它们都有相同的参数名。为了区分这两个参数,可以使用 this 关键字:

public class Person {
  private String name;
  private int age;
  
  public Person(String name, int age)
    this.name = name;
    this.age = age;
  
  
  public Person(String name) {
    this(name, 20); // 调用另一个构造方法
  }
}

在第二个构造方法中使用 this(name, 20) 调用第一个构造方法,这样就避免了重复定义代码的问题。

2. 在实例方法中使用 this 关键字

this 关键字可以在实例方法中使用,用于引用当前对象。例如,在一个类中,有一个实例方法 getName(),它返回当前对象的 name 属性:

public class Person {
  private String name;
  
  public Person(String name)
    this.name = name;
  
  
  public String getName()
    return this.name;
  
}

在 getName() 方法中返回 this.name,表示返回当前对象的 name 属性。

3. 在属性中使用 this 关键字

this 关键字可以在属性中使用,用于引用当前对象。例如,在一个类中,有两个属性 name 和 age,可以使用 this 关键字在构造方法中引用它们:

public class Person {
  private String name;
  private int age;
  
  public Person(String name, int age)
    this.name = name;
    this.age = age;
  
}

在构造方法中使用 this.name 和 this.age 表示引用当前对象的属性。

4. 在参数中使用 this 关键字

this 关键字可以在参数中使用,用于引用当前对象。例如,在一个类中,有一个方法 sameAge(),它接收一个 Person 类型的参数,可以使用 this 关键字引用当前对象和参数对象的 age 属性,并进行比较:

public class Person {
  private int age;
  
  public Person(int age)
    this.age = age;
  
  
  public boolean sameAge(Person other)
    return this.age == other.age;
  
}

在 sameAge() 方法中使用 this.age 和 other.age 表示引用当前对象和参数对象的 age 属性。

这篇文章介绍了 Java 中 this 关键字的四种用法:在构造方法、实例方法、属性和参数中使用。使用 this 关键字可以清晰明了地表达代码的含义,避免歧义和重复定义代码的问题。

关键词:Java、this、关键字、构造方法、实例方法、属性、参数。

  
  

评论区

请求出错了