Reputation: 2472
I need to declare an enum variable as a class member and need to define a setter and getter for that 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 color property as red, green or any from some other class and want to make decisions accordingly.
Upvotes: 7
Views: 41650
Reputation: 67790
If you want to work with your color
enum, you have to share its declaration more widely than you're doing. The simplest might be to put public
in front of enum color
in Vehicle.
Next, you need to declare a field of the enum's type. I suggest you change the name of the enum from color
to Color
, because it's basically a class anyway. Then you can declare a field: private Color color
among with your other fields.
To use the enum and especially its constants from another class, you need to be aware that the enum is nested in Vehicle. You need to qualify all names, so:
Vehicle.Color myColor = Vehicle.Color.RED;
Bakkal has kindly written code to demonstrate much of what I was talking about. See his answer for details!
Upvotes: 2
Reputation: 55448
The enum will have to be made public to be seen by the outside world:
public class Vehicle {
private String id;
private String name;
public enum Color {
RED, GREEN, ANY;
};
private Color color;
public Color getColor(){
return color;
}
public void setColor(Color color){
this.color = color;
}
}
Then from outside the package you can do:
vehicle.setColor(Vehicle.Color.GREEN);
if you only need to use Vehicle.Color inside the same package as Vehicle
you may remove the public
from the enum
declaration.
Upvotes: 18