11.3 this关键字
this调用构造方法 和 区*部变量与成员变量的同名情况:
构造方法调用格式:
this(参数列表);
实例代码:/*
* this可以在构造方法之间进行调用
* this.的方式,区*部变量和成员变量同名情况
* this在构造方法之间的调用,语法 this()
*/
public class Person {
private String name;
private int age;
public Person(){
//调用了有参数的构造方法
//参数李四,20传递给了变量name,age
this("李四",20);
}
/*
* 构造方法,传递String,int
* 在创建对象的同时为成员变量赋值
*/
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Test {
public static void main(String[] args) {
//创建Person的对象,调用的是空参数的构造方法
//运行的结果 null 0
Person p = new Person();
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
运行结果: