[英]Calling other methods and immutable instances
這是過去考試的一個問題。 我已經完成了問題,並且可以解決問題。 但是,我覺得我的實現可能很薄弱,例如我在整個Gregorian類中都使用static。
在給定每種情況的情況下,我有3種方法可以按照我認為合適的方式(在Gregorian類中)進行編寫。 我在Gregorian類的三種方法上使用static方法是正確的嗎?
另外,day,month和year字段是不可變的,是否將它們設置為足夠私有? (一旦創建,則不能更改字段值)
public class Date {
private int day;// needs to be immutable?
private String month;// needs to be immutable?
private int year;// needs to be immutable?
public Date(int theDay, String theMonth, int theYear) {
this.day = theDay;
this.month = theMonth;
this.year = theYear;
}
public int getDay() {
return day;
}
public String getMonth() {
return month;
}
public int getYear() {
return year;
}
}
public class Gregorian {
public static Date d;
public static boolean leapYear(){
if(d.getYear() %400==0 || (d.getYear()%4==0 && d.getYear()%100!=0)){
return true;
}else{
return false;
}
}
public static int getGregorianDateNumber(){
int a = (d.getYear()*384)*(32+d.getDay());
return a;
}
public static int getISO8601Date(){
int b = (d.getYear()*367)+d.getDay();
return b;
}
public static void main (String[] args){
d = new Date(9, "June", 8);
System.out.println(getGregorianDateNumber());
System.out.println(getISO8601Date());
System.out.println(leapYear());
}
}
取而代之的是靜態方法和靜態字段d
它們全部都是非靜態的。
public class Gregorian {
private final Date d;
public Gregorian(Date d_) {
this.d = d_;
}
public boolean isLeapyear() {
... // implemented as above
}
... // Other methods as above, but all non-static.
}
主要內容如下:
public static void main (String[] args){
Date d = new Date(9, "June", 8);
Gregorian g = new Gregorian(d);
System.out.println(g.getGregorianDateNumber());
System.out.println(g.getISO8601Date());
System.out.println(g.leapYear());
}
默認情況下,字符串是不可變的。
private int day;// needs to be immutable?
private int year;// needs to
不是您定義的不可變字段。 他們的狀態可以改變。 使其最終。
注意:將引用定為final並不意味着不能更改對象狀態(在您的情況下,此注釋無關緊要,因為您沒有引用對象)。
我會同意thinksteep的觀點-向您的字段添加“ final”將有助於防止更改它們。 沒有二傳手會加強這一點。
另外,我想指出一點
private String month;// needs to be immutable?
可以創建為從“一月”到“派”的任何內容。 如果我建議,請將其更改為一個枚舉,並確定允許的值數月。
public enum MonthName {
JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC;
}
將您的Date類更改為以下內容:
private final int day;
private final MonthName month;
private final int year;
public Date(int theDay, MonthName theMonth, int theYear) {
this.day = theDay;
this.month = theMonth;
this.year = theYear;
}
day
和year
都是原語,並且已經有不可變的int
版本,可以使用Integer
。
第二件事是,而不是在Gregorian
靜態引用Date
,將Date
作為參數傳遞給每個static
方法。 您可以確保線程安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.