的Answer by BrunoDM是正确的,应该被接受。
替代构造
这里有更多的代码,如由schwobaseggl的评论所说,以显示一个可选的构造以传递给Date类的另一个构造函数的参数。
请勿使用与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 ;
}
}
请更正您的代码片段/您使用date1和Date2声明Date对象是未声明的类。改用日期。 –