java —— this 关键字

@this关键字的用法

什么时候用this?

在程序产生二义性的时候,用 this 来指明当前对象;

  • 普通方法:this 指调用该方法的对象
  • 构造方法:this 指要初始化的对象
注意!!!

this 不能用于 static 方法中

只是看概念的话还是不行

撸代码:

/**
 * @author DREAM_yao
 * this关键字的用法
 */

/*this:创建好的当前对象对象的地址。
 * 构造方法:指向要初始化的对象
 * 
 * 普通方法:指向调用该方法的对象
 * */
class Score{
	int t1,t2;
	public Score(int t1) {
		this.t1=t1;
		/*必须位于构造方法的第一句*/
	}
	public Score(int t1,int t2){
		this.t1=t1;
		this.t2=t2;/*构造方法*/
	}
	public void getSum() {/*普通方法*/
		System.out.println(this.t1+this.t2);
	}
}
public class TestConstructor {
	public static void main(String[] args) {
		Score s1 = new Score(10);
		Score s2 = new Score(5,15);
		s2.getSum();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值