This关键字的使用
案例一:使用this关键字调用本类的属性和方法
class Persion {
private int age;
private String name;
//setter、getter、无参构造略
public Persion(int age, String name) {
this.age = age;
this.name = name;
this.getInfo();
}
public void getInfo() {
System.out.println("年龄:" + this.age + ",姓名:" + this.name);
}
}
public class ThisDemo {
public static void main(String[] args) {
Persion per = new Persion(18, "小明");
}
}
输出》》》
年龄:18,姓名:小明
面试题:下面的程序输出什么
class Persion {
private int age;
private String name;
public Persion(){
System.out.println("我是无参数的构造方法。");
}
public Persion(int age){
this.age = age;
System.out.println("我是只有一个参数的构造方法。");
}
//setter、getter略
public Persion(int age, String name) {
this.age = age;
this.name = name;
System.out.println("我是两个参数的构造方法。");
}
public void getInfo() {
System.out.println("年龄:" + this.age + ",姓名:" + this.name);
}
}
public class ThisDemo {
public static void main(String[] args) {
Persion per = new Persion(18, "小明");
per.getInfo();
}
}
输出》》》
我是两个参数的构造方法。
年龄:18,姓名:小明
以上代码我们在main方法中直接调用了对象的两个参数的构造方法,假设我想要调用无参数构造呢?
案例三:修改以上代码,同时输出 "我是无参数的构造方法"
class Persion {
private int age;
private String name;
public Persion(){
System.out.println("我是无参数的构造方法。");
}
public Persion(int age){
this.age = age;
System.out.println("我是只有一个参数的构造方法。");
}
//setter、getter略
public Persion(int age, String name) {
this();
this.age = age;
this.name = name;
System.out.println("我是两个参数的构造方法。");
}
public void getInfo() {
System.out.println("年龄:" + this.age + ",姓名:" + this.name);
}
}
public class ThisDemo {
public static void main(String[] args) {
Persion per = new Persion(18, "小明");
per.getInfo();
}
}
输出》》》
我是无参数的构造方法。
我是两个参数的构造方法。
年龄:18,姓名:小明
观察以上程序,通过添加了this(); 这行代码来实现构造方法之间的相互调用。
初学者思考:如何输出"我是只有一个参数的构造方法。"
注意:this(); 只能放在构造方法的首行,不然报以下的错误。
错误: 对this的调用必须是构造器中的第一个语句
this();
^
1 个错误