1、构造方法基础说明
1.1 说明
- 构造方法是一个特殊的方法,构造方法可以完成对象的创建,实例变量的初始化
- 当一个类没有设置构造方法时,系统默认会创建一个无参构造方法,而这个构造方法也称为(缺省构造器)
- 构造方法使用 new 运算符来调用
1.2 语法结构
public 访问修饰符
Student(形参列表) 和类名同名
{} 方法体
1.3 如何初始化实例变量
- 只有实例化构造器时才会给实例变量赋值,无参构造器赋默认值!
1.4 this()
注意:this()必须放在构造器内部的第一行,且只有一行
this()这种方式只能在用一个类当中使用。
this()属于语法规则,需要牢记
代码
package cc.linux.constructor_;
public class DateTest {
public static void main(String[] args) {
// 无参构造器使用this()调用有参构造输出默认年月日
Date d1 = new Date();
d1.detail();
// 有参构造器,需要传入实参
Date date2 = new Date(2022, 4, 10);
date2.detail();
}
}
class Date {
private int year;
private int month;
private int day;
public Date() {
// this()可以调用有参构造器,需要传入有参构造器的形参列表
this(1970, 1, 1);
}
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public void detail() {
System.out.println(year + "年" + month + "月" + day + "日");
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
}