java this

       java中this关键字的含义和用法

  

   this语句,用于构造函数之间互相调用

   示例:

public class MyThis {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestThis th = new TestThis();
		System.out.println(th.str);
	}

}

class TestThis{
	public String str;
	public TestThis(){
		this("hello");
	}
	public TestThis(String str){
		this.str = str;
	}
}


    

### Java `this` 关键字用法详解 在 Java 中,`this` 是一个关键字,用于引用当前类的实例。它主要用于解决成员变量与局部变量之间的命名冲突、调用其他构造方法以及明确指代当前对象。以下是 `this` 的主要用法及其详细解释: #### 1. 访问类中的成员变量 当方法参数或局部变量与成员变量同名时,可以通过 `this` 明确指代成员变量。例如: ```java public class Example { private int value; public void setValue(int value) { this.value = value; // 使用 this 指向成员变量 value } } ``` 在这个例子中,`this.value` 表示类的成员变量,而 `value` 则表示方法参数[^3]。 #### 2. 调用类中的成员方法 如果一个方法需要调用同一类中的另一个方法,可以使用 `this` 显式调用该方法。例如: ```java public class Example { public void method1() { System.out.println("这是 method1"); } public void method2() { this.method1(); // 使用 this 调用 method1 System.out.println("这是 method2"); } } ``` 这里 `this.method1()` 等价于直接调用 `method1()`,但在某些复杂场景下显式使用 `this` 可以提高代码可读性[^1]。 #### 3. 调用其他构造方法 在构造方法中,可以使用 `this` 来调用同一个类中的其他构造方法。这种用法必须放在构造方法的第一行。例如: ```java public class Example { private int value; public Example() { this(0); // 调用另一个构造方法 } public Example(int value) { this.value = value; } } ``` 上述代码中,无参构造方法通过 `this(0)` 调用了带参构造方法[^2]。 #### 4. 当前对象的引用 `this` 还可以作为当前对象的引用传递给其他方法或类。例如: ```java public class Example { public void displaySelf() { System.out.println(this); // 输出当前对象的引用 } } ``` 在这种情况下,`this` 表示当前实例的引用[^2]。 #### 5. 在继承中的行为 在继承关系中,`this` 的行为有所不同: - `this.xxx` 始终访问当前类(子类)的成员变量或方法。 - 如果子类重写了父类的方法,则 `this.yyy(paras…)` 调用的是子类的方法;否则调用父类的方法。 - 在构造方法中,`this(paras…)` 调用的是当前类的其他构造方法,而不是父类的构造方法。 ### 示例代码 以下是一个综合示例,展示了 `this` 的多种用法: ```java public class Example { private int value; public Example() { this(0); // 调用带参构造方法 } public Example(int value) { this.value = value; // 区分成员变量和局部变量 } public void setAndPrint(int value) { this.value = value; // 设置成员变量 this.printValue(); // 调用成员方法 } public void printValue() { System.out.println("Value: " + this.value); } public static void main(String[] args) { Example example = new Example(); example.setAndPrint(42); } } ``` ### 注意事项 - `this` 只能在非静态方法或构造方法中使用,因为静态上下文中没有实例的概念。 - 在构造方法中,`this` 必须出现在第一行,用于调用其他构造方法。 - 如果局部变量与成员变量名称相同,必须使用 `this` 来区分两者。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值