构造函数调用中传递参数的方式不同



我正在研究构造函数,我通过了这个例子

public class Time2
{
private int hour;
private int minute;
private int seconds;
public Time2()
{
this(0, 0, 0)
}
}

第二种方法是

public class Time2
{
private int hour;
private int minute;
private int seconds;
public Time2()
{
}
}

我在第二种方法中没有使用this(0,0,0)。以这种方式使用它们有什么区别?

如果我想在其中添加论点呢?

public Time2(int hour)
{
this(hour, 0, 0);
}

为什么我们需要添加null0,而不是不添加或根本不添加任何内容?

您必须提供一个重载/参数化的构造函数,才能在默认构造函数中使用它:

public class TimeTwo {
private int hour;
private int minute;
private int seconds;
public TimeTwo() {
/*
* the overloaded constructor is used here,
* you have to write this(...) because
* you want to initialize the current object
*/
this(0, 0, 0);
}
public TimeTwo(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.seconds = second;
}
}

另一种设置默认值的方法可以这样做:

public class TimeTwo {
private int hour;
private int minute;
private int seconds;
public TimeTwo() {
this.hour = 0;
this.minute = 0;
this.seconds = 0;
}
}

甚至还有第三种设置默认值的可能性:

public class TimeTwo {
private int hour = 0;
private int minute = 0;
private int seconds = 0;
public TimeTwo() {}
}
public Time2()
{
this(0,0,0)
}

public Time2()
{
}

如果Time2(int hour,int minute,int seconds)构造函数仅将传递给它的值分配给3个实例变量(小时、分钟和秒(,则将具有相同的行为,因为默认情况下这些实例变量将获得0值。

另一方面,如果Time2(int hour,int minute,int seconds)构造函数包含一些额外的逻辑(例如计算其他实例变量的值(,则无参数构造函数的这两种实现将具有不同的行为。

最新更新