Java : How to make enums inside java class

How to make enums inside java class

You can use enums inside a class as shown in the code below.

User.Gender.MALE or FEMALE is always associated with the user property. However if you need Gender to be generic and u want to use it with animals also, then you might want to keep this enum in a separate class.

package com.ekiras.demo;

public class User {
 
 public enum Gender{
  MALE,
  FEMALE
 }
 
 private String name;
 private String address;
 private String email;
 private String password;
 private Gender gender = Gender.MALE;
 
}

You can also use the enums with parameters inside class as shown below.

package com.ekiras.demo;

public class User {
 
 public enum Gender{
  MALE("male"),
  FEMALE("female");
  
  String value;
  Gender(String value){
   this.value=value;
  }
 }
 
 private String name;
 private String address;
 private String email;
 private String password;
 private Gender gender = Gender.MALE;
 
}
 

No comments :

Post a Comment