class Person {
private String name;
private int age;
// 构造方法中使用 this 关键字来区分参数和成员变量
public Person(String name, int age) {
this.name = name; // this.name 表示当前对象的成员变量 name
this.age = age; // this.age 表示当前对象的成员变量 age
}
// 使用 this 调用当前对象的其他方法
public void introduce() {
System.out.println("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
// 使用 this 返回当前对象的引用
public Person getPerson() {
return this;
}
// 使用 this 来调用另一个构造方法(构造器重载)
public Person(String name) {
this(name, 18); // 调用带两个参数的构造方法,默认年龄为 18
}
public static void main(String[] args) {
Person person1 = new Person("Alice", 25);
person1.introduce(); // 输出: Hello, my name is Alice and I am 25 years old.
Person person2 = new Person("Bob");
person2.introduce(); // 输出: Hello, my name is Bob and I am 18 years old.
}
}
构造方法中使用 this 关键字:在构造方法中,this 用于区分同名的参数和成员变量。例如,在 Person(String name, int age) 构造方法中,this.name 和 this.age 分别表示当前对象的成员变量,而 name 和 age 是传入的参数。
使用 this 调用当前对象的其他方法:在 introduce() 方法中,this.name 和 this.age 用于访问当前对象的成员变量。
使用 this 返回当前对象的引用:getPerson() 方法返回当前对象的引用,即 this。
使用 this 调用另一个构造方法:在 Person(String name) 构造方法中,this(name, 18) 调用了带两个参数的构造方法,并给定默认年龄为 18。
主方法演示:main 方法中创建了两个 Person 对象,并调用了 introduce() 方法来展示 this 的作用。
上一篇:java 弱引用
下一篇:java nohup
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站