当类没有声明构造方法的时候,就会使用默认的构造方法, 这个默认的构造方法就是“无参构造方法”
当类声明了有参构造方法的时候,默认构造方法就失去了本身的作用。
public class Client {
public static void main(String[] args) {
// 声明一个Cls3
Cls3 cls3;
// 获取Cls3 对象有两种方式
{
cls3 = new Cls3(); // 使用无参构造对象
cls3 = new Cls3("有参"); // 使用有参构造对象
}
// 声明一个Cls2
Cls2 cls2;
// 获取Cls2对象
{
// cls2 = new Cls2(); // 因为cls2只有一个有参构造方法,使用无参构造方法构造对象会出现编译错误。
cls2 = new Cls2("有参"); // 使用有参构造对象
}
// 声明一个Cls1
Cls1 cls1;
{
cls1 = new Cls1(); // 使用无参构造对象
}
}
}
// 定义一个默认构造方法的类
class Cls1 {
}
// 定义一个有参的构造方法类
class Cls2 {
Cls2(String arg) {
}
}
// 定义一个有参和无参两个构造方法的类
class Cls3 {
Cls3() {
}
Cls3(String arg) {
}
}
你看哈,我想知道当前时间,我这么输出:
System.out.println(new Date());
---输出结果:[Thu Jan 11 09:32:50 CST 2018]
同一个类,我这么用:
System.out.println(new Date(321312312));
---输出结果:[Mon Jan 05 01:15:12 CST 1970]
这就是构造函数,new的是同一个类,但是放的参数不同,返回的东西也不一样
不写构造函数时编译器会自动加上默认构造函数