Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare enum variable in Java bean

Tags:

java

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.

like image 860
Saurabh Avatar asked Jul 16 '10 17:07

Saurabh


1 Answers

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.

like image 165
bakkal Avatar answered Oct 13 '22 00:10

bakkal