gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:04:38 25 4
gpt4 key购买 nike

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

我得到了三种方法,可以用我认为合适的任何方式(在公历类(class)中)为每种方法给出一个场景。我对 Gregorian 类中的三个方法使用 static 是否正确。

此外,日、月和年字段应该是不可变的,将它们设置为私有(private)就足够了吗? (一旦创建,字段值就不能更改)

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)类公历{

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());
}

关于java - 调用其他方法和不可变实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com