调用其他方法和不可变实例



这是过去一次考试中的一道题。我已经完成了这个问题,它起作用了。然而,我觉得我的实现可能很弱,例如我在整个格里高利课堂上使用了静态。

我有三种方法可以用我认为合适的方式写作(在格里高利课堂上),每种方法都有一个场景。我在格里高利课堂上对这三种方法使用static是对的吗。

此外,日期、月份和年份字段是不可变的,将它们设置为私有字段是否足够?(一旦创建,字段值就无法更改)

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

不是您定义的不可变字段。他们的状态可以改变。让它们成为最终结果。

注:使引用成为最终值并不意味着对象状态不能更改(在您的情况下,此注释无关紧要,因为您没有引用对象)。

我同意thinkstrap的观点——在字段中添加"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;
}

dayyear都是基元,并且已经有了int的不可变版本,即Integer,您可以利用它。

第二件事是,与其在Gregorian中静态引用Date,不如将Date作为参数传递给每个static方法。那你就可以保证螺纹的安全了。

最新更新