constructor - JAVA call factory methods implicitly -
i have 1 constructor , 1 factory method date class. first 1 have 3 int parameter represent month, day , year. , second one, provide in case user give string 1 parameter represent month/day/year.
as can see in main(), forget call parseit, factory method. compiler still provide correct result. question is: can java call factory method implicitly?
please take 1st constructor , 2nd factory methods:
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 1/1/1: " + d1); d1 = new date("2/4/2"); system.out.println("date should 2/4/2: " + d1); } }
no, not. there no constructor takes in string, throw syntax error. in order make work, have define constructor takes in string
parameter performs same logic parseit(string)
function.
Comments
Post a Comment