繁体   English   中英

构造函数重载

[英]Constructor overload

这是我的课:

public class DateTime {

private int hours;
private int minutes;
private int seconds;
private int day;
private int month;
private int year;



public DateTime(int hours, int minutes, int seconds) {


    Calendar c = Calendar.getInstance();
    int day = c.get(Calendar.DAY_OF_MONTH);
    int month = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);

    this(hours,minutes,seconds,day,month,year); //Error: call to this must be first statement in constructor java

}


public DateTime(int hours, int minutes, int seconds, int day, int month, int year) {

    this.hours = hours;
    this.minutes = minutes;
    this.seconds = seconds;
    this.day = day;
    this.month = month;
    this.year = year;
}
}

我想用这种逻辑重载构造函数,
但是我得到了错误:
“对此的调用必须是构造函数java中的第一条语句”
你能建议一个解决方案吗?

因为“ this()”应该是构造函数要调用的第一个。 然后只有解决方案。 您可以这样使用:

public class DateTime {

private int hours;
private int minutes;
private int seconds;
private int day;
private int month;
private int year;



public DateTime(int hours, int minutes, int seconds) {

Calendar c = Calendar.getInstance();
this.day = c.get(Calendar.DAY_OF_MONTH);
this.month = c.get(Calendar.MONTH);
this.year = c.get(Calendar.YEAR);
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;

}
}

现在我认为这会很好。

有几种解决方案...

0)内联构造函数调用并直接设置小时分钟和秒,这是不值得的麻烦

1)使用中介构造函数

public DateTime(int hours, int minutes, int seconds) {
    this(hours, minutes, seconds, Calendar.getInstance());
}
private DateTime(int hours, int minutes, int seconds, Calendar c) {
    this(hours,minutes,seconds,c.get(Calendar.DAY_OF_MONTH),c.get(Calendar.MONTH),c.get(Calendar.YEAR));
}

2)使用工厂方法代替构造函数

public static DateTime newDateTime(int hours, int minutes, int seconds) {
    Calendar c = Calendar.getInstance();
    int day = c.get(Calendar.DAY_OF_MONTH);
    int month = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);
    return new DateTime(hours,minutes,seconds,day,month,year);
}

3)倒置依赖关系(每年的月份月份设置两次)

public DateTime(int hours, int minutes, int seconds, int day, int month, int year) {
    this(hours, minutes, seconds);
    this.day = day;
    this.month = month;
    this.year = year;
}

4)委托给方法而不是构造函数

public DateTime(int hours, int minutes, int seconds) {
    Calendar c = Calendar.getInstance();
    int day = c.get(Calendar.DAY_OF_MONTH);
    int month = c.get(Calendar.MONTH);
    int year = c.get(Calendar.YEAR);
    set(hours,minutes,seconds,day,month,year);
}
public DateTime(int hours, int minutes, int seconds, int day, int month, int year) {
    set(hours,minutes,seconds,day,month,year);
}
private final void set(int hours, int minutes, int seconds, int day, int month, int year) { ... }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM