java中this关键字

常见用法

  1. 引用当前对象的成员变量或方法:在一个类的方法中,如果参数名称与类的成员变量名称相同,可以使用“this”关键字来引用成员变量,以区分局部变量和成员变量。

  2. 在构造函数中调用其他构造函数:在一个类的构造函数中,可以使用“this”关键字来调用同一类的另一个构造函数。

  3. 返回当前对象的引用:在一个方法中,可以使用“return this;”语句来返回当前对象的引用。

  4. 将当前对象作为参数传递给其他方法:在一个类的方法中,可以使用“this”关键字将当前对象作为参数传递给其他方法。

demo示例

示例1:使用this关键字引用成员变量

构造函数中的参数与类的成员变量名称相同,因此可以使用this关键字引用成员变量。

public class Person {
   private String name;
   private int age;
   
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
   
   public void printPerson() {
      System.out.println("Name: " + this.name);
      System.out.println("Age: " + this.age);
   }
}

// 使用示例
Person person = new Person("Alice", 25);
person.printPerson();

示例2:使用this关键字调用其他构造函数

 第二个构造函数使用this关键字调用了第一个构造函数

public class Rectangle {
   private int width;
   private int height;
   
   public Rectangle(int width, int height) {
      this.width = width;
      this.height = height;
   }
   
   public Rectangle(int size) {
      this(size, size);
   }
}

// 使用示例
Rectangle rect1 = new Rectangle(10, 20);
Rectangle rect2 = new Rectangle(5);

示例3:使用this关键字作为方法参数

introduce()方法接受一个Person对象作为参数,使用this关键字引用当前对象,然后将当前对象和另一个Person对象一起传递给该方法

public class Person {
   private String name;
   
   public Person(String name) {
      this.name = name;
   }
   
   public void introduce(Person friend) {
      System.out.println("Hi, my name is " + this.name);
      System.out.println("My friend's name is " + friend.name);
   }
}

// 使用示例
Person alice = new Person("Alice");
Person bob = new Person("Bob");
alice.introduce(bob);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值