我有1個構造函數和1個工廠方法爲我的Date類。第一個只有3個int參數代表月,日和年。第二個,我提供的情況下,用戶將字符串作爲一個參數來表示月/日/年。你可以在main()中看到,我忘了調用工廠方法parseIt。但編譯器仍然提供正確的結果。所以問題是:JAVA可以隱式調用這個工廠方法嗎?隱含的JAVA調用工廠方法
請看看第一構造和第2工廠方法:
import java.io.*;
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
if (isValidDate(month, day, year)) {
this.month = month;
this.day = day;
this.year = year;
} else {
System.out.println("Fatal error: Invalid data.");
System.exit(0);
}
}
public static Date parseIt(String s) {
String[] strSplit = s.split("/");
int m = Integer.parseInt(strSplit[0]);
int d = Integer.parseInt(strSplit[1]);
int y = Integer.parseInt(strSplit[2]);
return new Date(m, d, y);
}
public static boolean isLeapYear(int year) {
if (year%4 != 0) {
return false;
} else if (year%100 == 0 && year%400 != 0) {
return false;
}
return true;
}
public static int daysInMonth(int month, int year) {
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
public static boolean isValidDate(int month, int day, int year) {
if (year < 1 || year > 9999 || month <= 0 || month > 12 || day <= 0) {
return false;
} else if (day > daysInMonth(month, year)) {
return false;
}
return true;
}
public static void main(String[] argv) {
Date d1 = new Date(1, 1, 1);
System.out.println("Date should be 1/1/1: " + d1);
d1 = new Date("2/4/2");
System.out.println("Date should be 2/4/2: " + d1);
}
}
你確定使用你的實現嗎?不是'java.util.Date'? – talex
Java不只是調用方法而不被告知... – Ryan
我沒有導入java.util。*只導入java.io. * – Patrick