解决问题:
我们在声明一个属性对应的 setxxx 方法时,通过形参给对应的属性赋值。如果形参名和属性名同名了,那么该如何在方法内区分这两个变量呢?
解决方案:
使用this关键字。使用this修饰的变量,表示的是属性。没有用this修饰的,表示的是形参。
1. this可以调用的结构:成员变量、方法
2. 使用方法:
2.1 针对于方法内的使用情况
- 一般情况,我们通过对象a调用方法,可以在方法内调用当前对象a的属性或其他方法。此时,我们可以在属性和其他方法前使用"this,",表示当前属性或方法所属的对象a。但是,一般情况下,我们都选择省略此"this,"结构。
- 特殊情况:如果方法的形参与对象的属性同名了,我们必须使用“th1."进行区分。使用this.修饰的变量即为属性(或成员变量没有使用this.修饰的变量,即为局部变量。
2.2 针对于构造器内的使用情况
- 一般情况,我们通过构造器创建对象时,可以在构造器内调用当前正在创建的对象的属性或方法。此时,我们可以在属性和方法前使用"this,",表示当前属性或方法所属的对象。但是,一般情况下,我们都选择省略此"this,"结构。
- 特殊情况,如果构造器的形参与正在创建的对象的属性同名了,我们必须使用"th1s,"进行区分。使用th1s,修饰的变量即为属性(或成员变量),没有使用this.修饰的变量,即为局部变量。
3. this调用构造器
- 格式:this(形参列表)
- 我们可以在类的构造器中,调用当前类中指定的其它构造器
- 要求:this(形参列表)“必须声明在当前构造器的首行
- 结论:this(形参列表)”在构造器中最多声明一个
- 如果一个类中声明了 n 个构造器,则最多有 n-1 个构造器可以声明有"this(形参列表)”的结构
public class thiseleven {
int price;
String name;
String constitute;
public void method1(){
System.out.println("这里是方法");
}
public void method2(){
System.out.println("名字是:" + name + " 价格是:" + price);
}
public thiseleven(){
System.out.println("这里是无参构造函数");
}
public thiseleven(String name, int price){
this(name);
this.price = price;
System.out.println("名字是:" + this.name + " 价格是:" + this.price);
}
public thiseleven(String name){
this.name = name;
}
}
public class thisele_test {
public static void main(String[] args) {
thiseleven me = new thiseleven();
me.name = "戴尔";
me.price = 10000;
me.method1();
me.method2();
thiseleven ma = new thiseleven("APPLE", 99999);
}
}