1

这是一个来自考试过去试卷的问题。我已经完成了这个问题并且它有效。但是,我觉得我的实现可能很弱,例如我在整个 Gregorian 类中使用静态。

给了我三种我认为合适的写法(在公历类中),每种方法都有一个场景。我在 Gregorian 类中的三个方法上使用 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());
}

}

4

4 回答 4

2

而不是静态方法和静态字段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());
}
于 2012-08-23T16:24:34.033 回答
1

默认情况下,字符串是不可变的。

private int day;// needs to be immutable?
private int year;// needs to

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

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

于 2012-08-23T15:03:14.517 回答
1

我同意 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;
}
于 2012-08-23T15:17:29.120 回答
1

两者dayyear都是原语,并且已经有int可用的不可变版本,Integer您可以使用它。

第二件事是,而不是静态引用Datein Gregorian,将 theDate作为参数传递给每个static方法。你可以保证线程安全。

于 2012-08-23T15:28:58.873 回答