Answer by BrunoDM 是正确的,应该被接受。
备用构造函数
这里是附加代码,正如 schwobaseggl 在评论中所建议的那样,显示了一个备用构造函数,该构造函数接受传递给日期类的另一个构造函数的参数。
不要使用与 Java 捆绑在一起的类中的名称来命名您自己的类。所以我使用名称MiniDate 而不是Date 以避免与java.util.Date 和java.sql.Date 混淆。顺便说一句,在实际工作中,从不滚动你自己的日期时间类,例如你的问题中看到的日期值。而是使用与 Java 捆绑在一起的 java.time 类。在这段代码中,我们将使用 LocalDate 而不是我们自己的 MiniDate 类。
见live code in IdeOne.com。
这里是main 方法,显示了Employee 的两个不同构造函数中的每一个。首先,我们传递MiniDate 的实例。在第二个中,我们将年-月-日整数传递给Employee 的构造函数,后者又将它们传递给MiniDate 的构造函数。
late-binding features of Java 会根据参数的数量和数据类型自动确定实际调用哪个构造函数。
顺便说一句,在实际工作中,将年月日的各个组成部分通过一个构造函数传递给另一个构造函数可能是一个糟糕的主意,既笨拙又令人困惑。 Java 缺少在Objective-C 和Swift 中运行良好的argument labels 来识别一长串参数。所以这里最好先实例化MiniDate(或者更好的是LocalDate),然后将完成的对象传递给构造函数以减少整体参数的数量。
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
MiniDate birthDate = new MiniDate( 1967 , 1 , 23 );
MiniDate hireDate = new MiniDate( 2016 , 2 , 28 );
Employee e1 = new Employee( "Wendy" , "Melvoin" , birthDate , hireDate );
System.out.println( e1 );
Employee e2 = new Employee( "Lisa" , "Coleman" , 1968 , 2 , 24 , 2016 , 4 , 14 );
System.out.println( e2 );
}
}
这里我们看到了那些构造函数,一个接受 MiniDate 类型的参数,另一个接受 int 字面量的参数。
class Employee {
private String firstName , lastName ;
private MiniDate birthDate , hireDate ;
// Constructor
public Employee( String firstNameArg , String lastNameArg , MiniDate birthDateArg , MiniDate hireDateArg ) {
this.firstName = firstNameArg;
this.lastName = lastNameArg;
this.birthDate = birthDateArg;
this.hireDate = hireDateArg;
}
// Constructor
public Employee( String firstNameArg , String lastNameArg , int birthYearArg , int birthMonthArg , int birthDayOfMonthArg , int hireYearArg , int hireMonthArg , int hireDayOfMonthArg ) {
this.firstName = firstNameArg;
this.lastName = lastNameArg;
this.birthDate = new MiniDate( birthYearArg , birthMonthArg , birthDayOfMonthArg );
this.hireDate = new MiniDate( hireYearArg , hireMonthArg , hireDayOfMonthArg );
}
@Override
public String toString() {
String s = "Employee{ name: " + this.firstName + " " + this.lastName + " | birthDate: " + this.birthDate + " | hireDate: " + hireDate + " }" ;
return s;
}
}
这里是MiniDate 的源代码。再次注意,在实际工作中,您将使用LocalDate 而不是您自己的类,例如LocalDate birthDate = LocalDate.of( 1967 , 1 , 23 ) ;。
请注意,我始终将日期部分排序为年-月-日。这遵循ISO 8601 标准的风格。我强烈建议您在日期时间工作中使用此标准的格式和样式。
class MiniDate {
// For teaching purposes only. In real work, use `LocalDate` class bundled with Java.
private int year , month , dayOfMonth ;
public MiniDate( int yearArg , int monthArg , int dayOfMonthArg ) {
this.year = yearArg;
this.month = monthArg;
this.dayOfMonth = dayOfMonthArg;
}
@Override
public String toString() {
// Generate string in standard ISO 8601 format, padding with zeros as needed.
String s = this.year + "-" + String.format( "%02d", this.month ) + "-" + String.format( "%02d", this.dayOfMonth ) ;
return s ;
}
}