- You can use the
enum type in Java 5 onwards for the purpose described. This is a safe type. - A is an instance variable. (If it has a static modifier, it becomes a static variable.) Constants simply mean that the value does not change.
- Instance variables are data members that belong to an object, not a class. Instance variable = instance field.
If you are talking about the difference between an instance variable and a class variable, an instance variable exists for every object created. Although the class variable has only one copy for each class loader, regardless of the number of objects created.
Java 5 and enum type
public enum Color{ RED("Red"), GREEN("Green"); private Color(String color){ this.color = color; } private String color; public String getColor(){ return this.color; } public String toString(){ return this.color; } }
If you want to change the value of the created enumeration, specify the mutator method.
public enum Color{ RED("Red"), GREEN("Green"); private Color(String color){ this.color = color; } private String color; public String getColor(){ return this.color; } public void setColor(String color){ this.color = color; } public String toString(){ return this.color; } }
Access Example:
public static void main(String args[]){ System.out.println(Color.RED.getColor());
Oh Chin Boon Oct 09 2018-12-12T00: 00Z
source share