Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an object from enum in Java?

Tags:

java

object

enums

I am have a number of classes which implement same interface. The objects for all those classes have to be instantiated in a main class. I am trying to do it in a manner with which this thing could be done in an elegant manner (I thought through enum). Example code :-

public interface Intr {
//some methods
}

public class C1 implements Intr {
// some implementations
}

public class C2 implements Intr {
// some implementations
}

...

public class Ck implements Intr {
// some implementations
}


public class MainClass {

enum ModulesEnum {
//Some code here to return objects of C1 to Ck
 FIRST {return new C1()},
 SECOND {return new C2()},
 ...
 KTH  {return new Ck()};
}

}

Now in the above example for some elegant way with which I can get instances of new objects of Class C1 to Ck. Or any other better mechanism instead of enum will also be appreciated.

like image 555
Siddharth Avatar asked Dec 26 '22 06:12

Siddharth


1 Answers

enum ModulesEnum {

  FIRST(new C1()), SECOND(new C2()); // and so on

  private ModulesEnum(Intr intr) { this.obj = intr; }
  private Intr obj;

  public Intr getObj() { return obj; }

}

Hope that helps. The trick is to add an implementation to every enum. If you want to access the object, use the getter.

ModulesEnum.FIRST.getObj();

If your Intr and its implementations are package protected, you can make ModulesEnum public to expose the implementations. This way you can have only one instance per implementation, making them singleton without using the pattern explicitly.

You can of course use a Factory too if you intend to have multiple instances for every implementation.

like image 180
Silviu Burcea Avatar answered Dec 27 '22 18:12

Silviu Burcea