声明后填充数组成员

时间:2017-02-14 18:02:32

标签: java constructor initialization

我的班级有一个阵列作为其成员之一。在构造函数中,我想将其成员填充到以下内容中。我怎么能这样做,它给了我一个错误。

public class GetCurrentMonth {

    Calendar now;
    String[] monthNames;

    /**
     * 
     */
    public GetCurrentMonth() {
        now = Calendar.getInstance();
        monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    }

    public String getMonth()
    {
        return monthNames[(now.get(Calendar.MONTH) + 1)];
    }
}

我不想在构造函数中添加这些月份名称,如下所示,因为我想遵循良好的编码习惯,并且我被告知所有初始化都应该在构造函数内完成。

String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

3 个答案:

答案 0 :(得分:4)

首先,不仅不是在构造函数中初始化的好习惯,它实际上是练习,因为:

  • 你实际上必须编写一个构造函数(添加无用的代码)
  • 字段应为static final,如果它们对于每个实例都相同,例如月份
  • 实例字段应尽可能final并在声明时初始化,如果只有一种方法可以初始化它们

最佳做法,包括遵守命名标准,表示您的课程应如下所示:

public class GetCurrentMonth {
    private static final String[] MONTH_NAMES = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    private final Calendar now = Calendar.getInstance();

    public String getMonth() {
        return MONTH_NAMES [(now.get(Calendar.MONTH) + 1)];
    }
}

答案 1 :(得分:3)

您需要使用新的String []

创建数组
monthNames = new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

答案 2 :(得分:0)

首先,我同意Bohemian♦的答案,但我甚至会更进一步,建议您创建一个包含月份名称的Enum。我将如何做到这一点:

public enum Month {
    JANUARY("January"), 
    FEBRUARY("February"), 
    MARCH("March"), 
    APRIL("April"), 
    MAY("May"),
    JUNE("June"), 
    JYLY("July"), 
    AUGUST("August"), 
    SEPTEMBER("September"),
    OCTOBER("October"), 
    NOVEMBER("November"), 
    DECEMBER("December");

    private String displayName;

    private Month(String displayName) {
        this.displayName = displayName;
    }

    @Override
    public String toString() {
        return displayName;
    }

    public static Month valueOfIgnoreCase(String value) {
        return valueOf(value.toUpperCase());
    }
}