第四节 构造方法 this关键字
4.1 构造方法
构造器是一个特殊的方法,这个特殊方法用于创建实例时执行初始化;
假如没有构造方法,系统会自动生成一个默认的无参构造方法;假如有构造方法,系统不会自动生成构造方法;
public class People {
//String类属性默认值是Null
private String name;
//int类属性默认值是0
private int age;
/*
* 默认构造方法
*/
/* People(){
System.out.println("默认构造方法");
}
/*
* 有参数的构造方法(构造方法的重载)
*/
People(String name2,int age2){
name=name2;
age=age2;
System.out.println("有参数的构造方法!");
}
public void say() {
System.out.println("我叫"+name+",我今年"+age+"岁了!");
}
public static void main(String[] args) {
//People people=new People();
People people2=new People("张三",23);
people2.say();
}
}
有参数的构造方法!
我叫张三,我今年23岁了!
4.2 this关键字
this 表示当前对象
1,使用this 调用本类中的属性;
2,使用this 调用构造方法;
public class People2 {
//String类属性默认值是Null
private String name;
//int类属性默认值是0
private int age;
/*
* 默认构造方法
*/
People2(){
System.out.println("默认构造方法");
}
/*
* 有参数的构造方法(构造方法的重载)
*/
People2(String name,int age){
this();
this.name=name;
this.age=age;
System.out.println("有参数的构造方法!");
}
public void say() {
System.out.println("我叫"+name+",我今年"+age+"岁了!");
}
public static void main(String[] args) {
//People people=new People();
People2 people2=new People2("张三",23);
people2.say();
}
}