Java中的关键词this

今天早上突然想起来java中有个key word叫this,以前都没怎么注意,于是写下帮助记忆。

package org.iteye.bbjava.thistest;

public class ThisTest {
	private String thisStr="The key word 'this'!";
	public ThisTest(){

	}

	//this引用构造方法
	public ThisTest(String thisStr){
		this();
		this.thisStr=thisStr;//特别指出,当前使用的是实列变量,而不是静态变量或局部变量。
	}
	public ThisTest(UseThisTest utt){
		System.out.println("Hello!my name is "+utt);
	}

	//
	public void test(){
		System.out.println(this.thisStr);
		System.out.println("The key word 'this' in the ThisTest class:  "+this);
	}

	//返回当前实列
	public ThisTest returnMyself(){
		return this;
	}


	public static void main(String []args){
		ThisTest tt=new ThisTest();
		tt.test();
		System.out.println("returnMyself:"+tt.returnMyself());
	}
}


程序运行输出:


The key word 'this'!
The key word 'this' in the ThisTest class: org.iteye.bbjava.thistest.ThisTest@de6ced
returnMyself:org.iteye.bbjava.thistest.ThisTest@de6ced
 

  • 代码示例:
package org.iteye.bbjava.thistest;

public class UseThisTest {
	private ThisTest tt = new ThisTest();

	public void test(){
		System.out.println("Do nothing!");
	}
	public void callTest(){

		ThisTest utt1 = new ThisTest(this);//把当前对象作为参数传传递。
		this.tt.test();
		System.out.println("The key word 'this' in  the UseThisTest class:"+this);
	}
	public static void main(String []args0){
		UseThisTest utt = new UseThisTest();	
		utt.test();
		utt.callTest();
	}
}


程序运行输出:

Do nothing!
Hello!my name is org.iteye.bbjava.thistest.UseThisTest@c17164
The key word 'this'!
The key word this in ThisTest:org.iteye.bbjava.thistest.ThisTest@1fb8ee3
The key word 'this' in the UseThisTest class:org.iteye.bbjava.thistest.UseThisTest@c17164
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值