Declare enumeration variables in Java beans
•
Java
I need to declare an enumeration variable as a class member and define a setter and getter for it like a java bean Something like this –
public class Vehicle { private String id; private String name; enum color { RED,GREEN,ANY; } // setter and getters }
Now, I want to set the color property to red, green, or any other class and want to make a decision accordingly
Solution
Enum must be made public for the outside world to see:
public class Vehicle { private String id; private String name; public enum Color { RED,ANY; }; private Color color; public Color getColor(){ return color; } public void setColor(Color color){ this.color = color; } }
Then from outside the bag you can do:
vehicle.setColor(Vehicle.Color.GREEN);
If you only need to use vehicle in the same package as vehicle Color, you can delete public from the enumeration declaration
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码