对象的构造及初始化

一、如何初始化对象

在Java方法内部定义一个局部变量时,必须要初始化,否者会编译失败(如下)

public static void main(String[] args) {
int a;
System.out.println(a);
}
// Error:(26, 28) java: 可能尚未初始化变量a,改为int a=10;则可以
//如果是对象则:

public static void main(String[] args) {
Date d = new Date();
d.printDate();  
d.setDate(2021,6,9);  //调用类里面的setDate方法,较为麻烦
d.printDate();
} 

二、构造器

构造方法 ( 也称为构造器 ) 是一个特殊的成员方法, 名字必须与类名相同,在创建对象时,由编译器自动调用,并且 在整个对象的生命周期内只调用一次。( 构造方法的作用就是对对象中的成员进行初始化,并不负责给对象开辟空间
格式:                       public 类名([参数]){
                                                                            语句;
                                                                    }
1、无(有)参构造器:
public class Date {
public int year;
public int month;
public int day;
// 无参构造方法
public Date(){
this.year = 1900;
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(); //调用无参的构造器,结果是1900-1-1
//Date d=new Date(1234,3,4);
//d.printDate();   如果用这两行,调用的是有参构造器,则结果是1234-3-4
}
}

上述两个构造方法:名字相同,参数列表不同,因此构成了方法重载

当程序中既没有有参也没写无参构造器的时候,系统编译器默认会生成一个无参构造器,一旦写了构造器,编译器则不会在生成。

三、无参和有参构造器之间的关系

public class Date {
public int year;
public int month;
public int day;

public Date(){
//System.out.println(year); 注释取消掉,编译会失败(因为不在第一行)
this(1900, 1, 1);   // 无参构造方法--内部给各个成员赋值初始值,该部分功能与三个参数的构造方法重复
                    // 此处可以在无参构造方法中通过this调用带有三个参数的构造方法
                    // 但是this(1900,1,1);必须是构造方法中第一条语句
//this.year = 1900;
//this.month = 1;
//this.day = 1;
}
// 带有三个参数的构造方法
public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
}

无参的构造器可以调用三个参数的构造器,反过来三个参数的构造器则不能调用无参

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值