关于this关键字的学习和使用

this在代码中是怎么使用的。

其实可以顾名思义的想象 this关键字 代表的含义就是类的本身,你可以想象一下,当成员变量名与方法中的参数名重复的时候,怎么来调用成员变量呢,下面看一段代码。

this调用成员变量

//
public class Apple { 
	String name="apple";
	
    public void Appled(String name) {
    	System.out.println(name);
    }
    
    
	
	public static void main(String[] args) {
		Apple apple =new Apple();
		apple.Appled("123");
	}
}

思考一下,上面的代码输出的值是什么?没错,是:123,那么怎么才能调用到成员变量的值呢。可以使用this关键字,看下面修改过的代码片段

public class Apple {
	String name="zhangm";
	
    public void Appled(String name) {
    	System.out.println(this.name);
    }
    
    
	
	public static void main(String[] args) {
		Apple apple =new Apple();
		apple.Appled("123");
	}
}

可以看到在Appled方法中使用this关键字,就可以来调用成员变量的值,输出结果为:zhangm
——————————————————————————————————————————————————————

this关键字不仅可以调用本身类的变量和方法,还可以调用自身的构造方法

假如说我有一个鸡蛋饼的类,大家在买鸡蛋饼的时候默认放一个鸡蛋,当有需求的时候可能会加更多的鸡蛋

package beifendadai;

public class EggCake {
	int eggCount;
	public EggCake(int eggCount) {
		this.eggCount=eggCount;
		System.out.println("鸡蛋饼里有"+this.eggCount+"个鸡蛋");
		
	}
	public EggCake() {
		this(1);//调用有参数的构造方法。
	}
	
	public static void main(String[] args) {
		EggCake e1=new EggCake(5);
		EggCake e2=new EggCake();
	}
}

可以看到如果调用鸡蛋饼类的有参的构造方法 鸡蛋饼里就会有5个鸡蛋,默认的是放1个鸡蛋(使用this()的方式可以调用有参数的构造方法)

以上是本人学习java的this关键字的学习记录,欢迎随时指正~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值