Java This 关键字

本文详细介绍了Java中this关键字的作用和使用场景,包括区分实例变量和局部变量、在方法中引用当前类实例、作为参数传递以及在构造器中的应用。通过示例代码展示了this如何消除变量混淆,以及在不同情况下如何正确使用。

This key word in Java

A lot of people must know how to use “this” in java programming, but do they really know what exact This is and why does it exist ?

1 - Why we need to use “This” in java?

class Student{
	int number;
	int age;// two instance variables
	public void setStudent(int number, int age){// two arguments
		number = number;
		age = age;
	}
	public void display(){
		System.out.println(number);
		System.out.println(age);
	}
	public void main(String[] args){
		Student s = new Student(123, 18);
		s.display();
	}
}
result: 0
        0
  1. In the setStudent method, two arguments are declared as number and age.
  2. In the Student class, two instance variables are named as number and age.
  3. When the code are executed, the compiler gets confused. whether the left side of operator is instance variable or local variable. So, it will not set the data to number and age when the setStudent method is called.
So we need to use this key word to remove confusion between instance variables and local variables. (using this to refer to instance variables of a method or constructor)

2 - How to use this in java ?

1) using this to refer instance variable of current class.

eg 1.
class Student{
	int number = 100;// instance variable
	int age = 100;
	public void show(){
		System.out.println(this.number);// or number 
		System.out.println(this.age);// or age
    }
    public static void main(String[] args){
		Student s = new Student();
		s.show();
	}
}
result: 100
		100
eg 2.
class Student{
	int number = 100;// instance variable
	int age = 100;
	public void setStudent(int number, int age){
		this.number = number;// left this.number is instance variable in student class, right number is the argument that was given in main class
		this.age = age;
	}
	public void show(){
		System.out.println(this.number);// or number 
		System.out.println(this.age);// or age
    }
    public static void main(String[] args){
		Student s = new Student(1, 1);
		s.show();
	}
}
result: 1
		1

2)using this to pass method as an argument

class Student{
	int number = 100;// instance variable
	public void setStudent(int number){
		this.number = number; 
		this.display();
	}
	public void show(){
		System.out.println(this.number);
    }
    public void display(){
		System.out.println("invoking display method");
	}
    public static void main(String[] args){
		Student s = new Student(1);
		s.show();
	}
}
result: invoking display method
		1

3) using "this()"invoking current constructor

class Student{
	student(){
		System.out.println("invoking first constructor");
	}
	student(int number){
		this();
		Sytem.out.println(number);
	}
	public static void main(String[] args){
		Student s = new Student(100);
	}
}
result: invoking first constructor 
		100

4) using this to return the current class instance (passing the class instance)

class Student{
	void print(){
		System.out.println(this);
	}
	public static void main(String[] args){
		Student s = new Student();
		System.out.println(s);
		s.print();
	}
}
result: Student@1540e19d (class instance ID)
		Student@1540e19d
class Person{
	void mom(Person p){
		System.out.println("invoking mom method");
	}
	void dad(){
		mom(this);
	}
	public static void main(String[] args){
		Person p = new Person();
	    p.dad();
	}
}
result: invoking mom method
### Java 中 `this` 关键字的用法 #### 1. 引用当前类实例本身 在 Java 的类中,`this` 可以用来引用当前类的实例。它表示的是当前对象自己,在某些场景下非常有用[^3]。 ```java public class Student { private String name; public Student(String name) { this.name = name; // 使用 this 来区分成员变量和局部变量 } public Student getStudent() { return this; // 返回当前对象本身 } } ``` --- #### 2. 解决成员变量与局部变量命名冲突 当方法参数或局部变量的名字与类中的成员变量相同的时候,可以通过 `this` 明确指定访问的是成员变量而不是局部变量[^1]。 ```java public class Person { private int age; public void setAge(int age) { this.age = age; // this.age 表示成员变量,age 表示局部变量 } } ``` --- #### 3. 调用本类中的其他构造函数(重载构造器) `this()` 可以用于调用同一类中的其他构造函数,通常出现在多个构造函数的情况下。需要注意的是,`this()` 必须放在构造函数的第一行[^4]。 ```java public class Car { private String model; private double price; public Car(String model) { this(model, 0); // 调用带两个参数的构造函数 } public Car(String model, double price) { this.model = model; this.price = price; } } ``` --- #### 4. 传递当前对象作为参数 有时候需要将当前对象作为一个参数传递给其他方法,这时可以直接使用 `this` 将整个对象传入[^5]。 ```java class A { public void display(B b) { System.out.println("Display method called"); } } class B { public void call(A a) { a.display(this); // 将当前对象 (B 类型) 作为参数传递 } } public class Test { public static void main(String[] args) { A objA = new A(); B objB = new B(); objB.call(objA); } } ``` --- #### 5. 创建匿名对象并立即使用 如果某个对象只需要被使用一次,则可以创建一个匿名对象,并通过 `this` 进行操作[^4]。 ```java class Demo { public Demo() {} public void show() { System.out.println("This is an anonymous object."); } } public class MainClass { public static void main(String[] args) { new Demo().show(); // 创建匿名对象并直接调用其方法 } } ``` --- ### 总结 `this` 是 Java 面向对象编程中的一个重要关键字,主要用于解决成员变量与局部变量同名的问题、调用其他构造函数、返回当前对象以及传递当前对象作为参数等场景。合理使用 `this` 可以使代码更加清晰简洁[^1][^2][^3][^4][^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值