我正在研究构造函数,并且通过了这个示例
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);
}
为什么我们需要添加null
或0
而不是不添加或根本不添加任何内容?
最佳答案
您必须提供一个重载/参数化构造函数才能在默认构造函数中使用它:
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() {}
}
关于java - 使用不同的参数传递方式调用构造函数的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722046/