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.

Example 1

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

Example 2

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 contarct job

Updated on: 23-Nov-2023

893 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements