在此是在Java中的关键字,其被用作当前类的对象的引用在一个实例方法或构造,与。使用此方法,您可以引用类的成员,例如构造函数,变量和方法。
使用“ this”,您可以-
如果实例变量与局部变量在构造函数或方法中具有相同的名称,则将它们区分。
class Student { int age; Student(int age) { this.age = age; } }
在类中从其他类型调用一种类型的构造函数(参数化的构造函数或默认类型)。这称为显式构造函数调用。
class Student { int age Student() { this(20); } Student(int age) { this.age = age; } }
public class This_Example { // Instance variable num int num = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(int num) { // Invoking the default constructor this(); // Assigning the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println("Hi Welcome to Nhooo"); } public void print() { // Local variable num int num = 20; // Printing the local variable System.out.println("value of local variable num is : "+num); // Printing the instance variable System.out.println("value of instance variable num is : "+this.num); // Invoking the greet method of a class this.greet(); } public static void main(String[] args) { // Instantiating the class This_Example obj1 = new This_Example(); // Invoking the print method obj1.print(); // Passing a new value to the num variable through parametrized constructor This_Example obj2 = new This_Example(30); // Invoking the print method again 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 Nhooo 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 Nhooo