系列文章目录
Java中的类和对象系列
第一章 this详解
第二章 构造方法
前言
构造方法是一个特殊的成员方法,名字必须与类名相同,在创建对象时,又编译器自动调用,且只调用一次。
一、构造方法是用来干什么的呢?
构造方法的作用就是对对象中的成员进行初始化,并不负责给对象开辟空间。
二、使用方法
1.特性
1、名字必须与类名相同
2、没有返回值类型,设置为void也不行
3、创建对象时自动调用,且在对象的生命周期内仅能调用一次
4、构造方法可以重载
public class Date {
public int year;
public int month;
public int day;
//无参构造方法
public Date() {
this.year = 2020;
this.month = 1;
this.day = 1;
}
//带有三个参数的构造方法(方法重载)
public Date(int year,int month,int day){
this.year = year;
this.month = month;
this.day = day;
}
public void printDate(){
System.out.println(year+"/"+month+"/"+day);
}
public static void main(String[] args) {
Date d = new Date();
d.printDate();
}
}
2.如果构造参数没有定义,默认无参构造
public class Date {
public int year;
public int month;
public int day;
public void printDate(){
System.out.println(year+"/"+month+"/"+day);
}
public static void main(String[] args) {
Date d = new Date();
d.printDate();
}
}
注:一旦定义了构造函数,系统就不会再默认生成
3. this调用其它构造方法简化代码
详情可见本系列第一章this详解
重点用于构造方法的重载!