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关键字的学习记录,欢迎随时指正~