Java学习之this用法

this关键字在平时java程序中经常遇到,有必要了解下具体的用法。

1,调用当前对象本身

package com.test.xuyz;

public class TestThis {

	String s = "test";
	
	public TestThis(String s){
		System.out.println("这个S是 " + s);
		System.out.println("1,这时this.s是 "+this.s);
		this.s = s;
		System.out.println("2,这时this.s是"+this.s);
	}
	
	public static void main(String[] args) {
		TestThis test = new TestThis("testtesttest");
		System.out.println("这个S是 " + test.s);
	}
}
运行结果:

这个S是 testtesttest
1,这时this.s是 test
2,这时this.s是testtesttest
这个S是 testtesttest

在这个例子中,构造函数TestThis中的参数与成员变量同名,如果直接对s操作则是直接操作参数s,如果想操作成员变量则需要用this进行引用。

2,通过this调用另一个构造方法,用法:this(参数列表),这个仅仅在类的构造方法中使用

package com.xuyz.test;

public class TestThis {

	public TestThis(String s){
		System.out.println("String constructor:  " + s);
	}
	
	public TestThis(int i ,String s){
		this(s);
		i++;
		System.out.println("TestThis:"+i+",S is "+s);
	}
	
	public static void main(String[] args) {
		new TestThis(20,"hao");
	}
}
运行结果:

String constructor:  hao
TestThis:21,S is hao

3,表示对当前对象的引用

package com.xuyz.test;

public class TestThis {

	private int i = 0;
	
	public TestThis test(){
		this.i++;
		return this;
	}
	
	public static void main(String[] args) {
		TestThis tt = new TestThis();
		System.out.println(tt.test().test().i);
	}
}
运行结果:

2

注意:this关键字不能出现在static方法中。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值