构造方法
- 没有返回值,方法名与类名相同
- 调用完构造方法后,对象才真正存在
- 利用2,来解释this代表 当前对象的引用,而不是当前对象
class Student {
private String name;
private int age = 176;
public static int count = 99;
public Student() {
System.out.println("student()");//1无参 构造方法
}
public Student(String name) {
System.out.println("student(String)");//2有一个String类的 构造方法
this.name = name;
}
public Student(String name, int age) {//3两个参数的 构造方法
this.name = name;
this.age = age;
}
public static void main1(String[] args) {
Student student = new Student();//调用无参构造方法
Student student2 = new Student("gaobo");//调用一个参数的构造方法
}
注意事项
- 当类中没有写任何的构造方法时,编译器会自动提供一个 无参的构造方法 ,这个方法什么都没做
- 当在类中写了其他的构造方法,那么编译器不会自动提供构造方法
- 构造方法可以 重载
1.方法名相同
2.参数列表不同
3.返回值不做要求
4.在一个类中
在一个构造方法中调用另一个构造方法(this)
利用this调用另一个构造方法时,一定要放在此构造方法的第一行!