天天看点

Java基础:五、默认构造器(3)

默认构造器

默认构造器(又名“无参”构造器)是没有形式参数的—它的作用是创建一个默认对象。如果你写的类中没有构造器,则编译器会自动帮你创建一个默认构造器。

class Test03{}
class Test04{
    public static void main(String[] args) {
        Test03 test03 = new Test03();
    }
}           

复制

new Test03()

创建了一个新对象,并调用默认构造器-即使你没有明确定义它。

但是如果已经定义了一个构造器(无论是否有参数),编译器就不会帮你自动创建默认构造器

class Test03{    
    Test03(int i){}
    Test03(double d){}
}
class Test04{
    public static void main(String[] args) {
        // Test03 test01 = new Test03(); // 编译器会报错
        Test03 test02 = new Test03(1);
        Test03 test03 = new Test03(1.0);
    }
}           

复制