Duplicate static field (Array vs String)
I have a question about the following code:
public Class Settings{
public static final String WelcomeMessage= "helloworld";
public static final String ByeMessage= "yo";
public static String[] widgets = {WelcomeMessage,ByeMessage};
}
The compiler complains about duplicat variables. Can I delete the 2 separate variables and still acces WelcomeMessage by Settings.WelcomeMessage? I don't need to acces it by Settings.widget[0]? And is it possible to add another variable to the WelcomeMessage variable (by for instance using a static hashtable)?
Edit: I know this code doesn't look right but it's just an example because I wondered why the compiler t开发者_运维问答hinks WelcomeMessage (as a separata variable) is the same as the variable in the Widgets array.
I would consider java-enums in your case:
public enum Settings {
WelcomeMessage ("helloworld"),
ByeMessage ("yo");
public final String value;
Settings(String value) {
this.value = value;
}
}
You can access now the values via Settings.WelcomeMessage.value
. Also you get a List of the enums with Settings.values()
.
You've marked the fields as public static which means that yes you'll be able to access them via:
Settings.WelcomeMessage
or if you you use a static import in your class, just:
WelcomeMessage
You haven't actually used these constants in the widgets array, you've just created two new strings in there "WelcomeMessage" and "ByeMessage"
public static String[] widgets = {"WelcomeMessage","ByeMessage"};
No, if you delete the WelcomeMessage and ByeMessage constants you can't access them in that way, you'd have to go through the widgets array and access them as:
Settings.widgets[0]
I think you meant to use this instead:
public Class Settings
{
public static final String WelcomeMessage= "helloworld";
public static final String ByeMessage= "yo";
public static String[] widgets = {WelcomeMessage,ByeMessage};
}
But this is better:
public Class Settings
{
public static String[] widgets = {"WelcomeMessage","ByeMessage"};
}
And yes you can access WelcomeMessage
via Settings.widgets[0]
.
Edit: Oops - yep - of course you cannot access them by name, only index into the array.
Edit 2: If you make the field protected or private and provide 'getter' methods, then it doesn't matter to any user classes how they are implemented:
public Class Settings
{
private static final String welcomeMessage= "helloworld";
private static final String byeMessage= "yo";
public static String getWelcomeMessage()
{
return welcomeMessage;
}
public static String getByeMessage()
{
return byeMessage;
}
}
精彩评论