Computer >> Computer tutorials >  >> Programming >> Java

What is a Type-safe Enum in Java?


The enums are type-safe means that an enum has its own namespace, we can’t assign any other value other than specified in enum constants. Typesafe enums are introduced in Java 1.5 Version. Additionally, an enum is a reference type, which means that it behaves more like a class or an interface. As a programmer, we can create methods and variables inside the enum declaration.

Example1

import java.util.*;
enum JobType {
   permanent,
   contract
}
public class EnumTest1 {
   public static void main(String []args) {
      print(JobType.values());
   }
   public static void print(JobType[] list) {
      for (int i=0; i < list.length; i++) {
         System.out.println(list[i]);
      }
   }
}

Output

permanent
contract


Example2

enum JobType {
   permanent {
      public void print(String str1) {
         System.out.println("This is a permanent " + str1);
      }
   },
   contract {
      public void print(String str2) {
         System.out.println("This is a contarct " + str2);
      }
   };
   abstract void print(String name);
}
public class EnumTest2 {
   public static void main(String[] args) {
      JobType dt1 = JobType.permanent;
      JobType dt2 = JobType.contract;
      dt1.print("job");
      dt2.print("job");
   }
}

Output

This is a permanent job
This is a contract job