Java第二十四篇:详述关键字this

正在查阅这篇文章的你,肯定是一个爱学习的人儿~

说到关键字this,给我印象最深的地方就是在对成员变量进行封装的时候setter方法中书写this,如this.x=x等,这个地方是为了区分成员变量和局部变量,但this的用法远不止这一种,一起来看看:
1.在类的构造方法中书写关键字this

public class Study{
	public static void main(String args[]) {
		Study1 study =new Study1();
	}
}
class Study1{
	public Study1() {
		this.add(1,2);//表示在创建对象时调用了add()方法
	}
	public void add(int a,int b) {
		int c=a+b;
		System.out.println("c="+c);
	}
}

结果显示:
在这里插入图片描述
补充点:
在构造方法内部书写this,可指另外的构造方法(不能指非构造方法),如:

public class Study{
	public static void main(String args[]) {
		Study1 study1 =new Study1();
		Study1 study2 = new Study1(2,4);
	}
}
class Study1{
	public Study1() {
		this(2,3);//调用带有参数的构造方法且该行代码必须放在方法的第一行,否则会报错
		this.add(1,2);//表示该对象构造自己的时候调用了add()方法
		
	}
	public Study1(int a,int b) {
		a=a*b;
		System.out.println("a="+a);
		
	}
	public void add(int a,int b) {
		int c=a+b;
		System.out.println("c="+c);
	}
}

结果显示:
在这里插入图片描述
2.在实例方法中书写关键字this,表示使用该方法的对象

public class Study{
	public static void main(String args[]) {
		Study1 study1 =new Study1();
		study1.add(11);
	}
}
class Study1{
	int x=0;
	public void add(int a) {
		this.x=a+a; //代表该方法的对象
		System.out.println("x="+x);
		this.fun(this.x);
	}
	public void fun(int a) {
		System.out.println("a*a="+a*a);
	}
}

结果显示:
在这里插入图片描述
3.使用关键字this区分成员变量和局部变量

public class Study{
	public static void main(String args[]) {
		Study1 study1 =new Study1();
		study1.add(11,22);
	}
}
class Study1{
	int x=12,y=13;
	public void add(int x,int y) {
		this.x=x+y;
		System.out.println("this.x="+this.x);
		System.out.println("x="+x);
	}
}

结果显示:
在这里插入图片描述
过程分析:
在上述类中 ,成员变量和局部变量的名称相同,则成员变量就会被隐藏,若想使用成员变量,在前面加this就行,见输出结果图。
总结:

1.在类的构造方法中书写关键字this;
2.在实例方法中书写关键字this,表示使用该方法的对象;
3.使用关键字this区分成员变量和局部变量。

使用关键字this需要注意:关键字this不能用在静态环境中,否则会报错,如下:
在这里插入图片描述
Cannot use this in a static context(不能在静态上下文中使用关键字this)

有疑问欢迎留言!

点个赞,加个关注呗!嘿嘿!

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值