Reputation: 171
My class has an array as one of it's members. Inside the constructor, I want to populate it's members to the following. How can I do that, it gives me an error.
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)];
}
}
I do not want to add these month names at the constructor as follows, since I want to follow good coding practice, and I was told that all initializations should be done inside the constructor.
String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Upvotes: 1
Views: 62
Reputation: 7808
First, I agree with the answer from Bohemian♦, But I even would go further and recommend that you create an Enum that holds your month names. Here is how I would do it:
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());
}
}
Upvotes: 0
Reputation: 425328
Firstly, not only is it not good practice to initialize in the constructor, it's actually bad practice, because:
static final
if they're the same for every instance, like the monthsfinal
where possible and be initialised on declaration if there's only one way to initialize themBest practice, including adhering to naming standards, says your class should look like this:
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)];
}
}
Upvotes: 4
Reputation: 2445
You need to create the array with new String[]
monthNames = new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Upvotes: 3