this是Java中的一个关键字,用作对当前类对象的引用,在实例方法或构造函数中。 使用它可以引用类的成员,例如:构造函数,变量和方法。
注 -
this关键字仅在实例方法或构造函数中使用。
通常,this关键字用于 -
class Student {
private int age;
Student(int age) {
this.age = age;
}
}
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
以下是使用this关键字访问类成员的示例 -
public class ThisExample {
// 实例变量:num
int num = 10;
ThisExample() {
System.out.println("This is an example program on keyword this");
}
ThisExample(int num) {
// 调用默认构造方法
this();
// 将局部变量 num 分配给实例变量 num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Yiibai");
}
public void print() {
// 局部变量:num
int num = 20;
// 打印局部变量
System.out.println("value of local variable num is : "+num);
// 打印实例变量
System.out.println("value of instance variable num is : "+this.num);
// 调用类方法
this.greet();
}
public static void main(String[] args) {
// 实例化该类
ThisExample obj1 = new ThisExample();
// 调用 print 方法
obj1.print();
//通过参数化构造函数将新值传递给 num 变量
ThisExample obj2 = new ThisExample(30);
// 再次调用 print 方法
obj2.print();
}
}
执行上面示例代码,得到以下结果 -
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Yiibai
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Yiibai