Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an enum class which contains objects of another non-enum class in Java?

Tags:

java

enums

For example, I have Subscriber class and its objects subscriber1, subscriber2, subscriber3. Is it possible to create an enum that contains these objects? I'm trying to do this

enum Subscribers{
    subscriber1,subscriber2,subscriber3;
}

But I'm getting strings subscriber1,subscriber2,subscriber3 instead. I would appreciate any feedback

like image 482
SaintSammy Avatar asked Dec 16 '21 18:12

SaintSammy


2 Answers

No. Enum constants inherit from the enum class.

From the Java Language Specification:

8.9.1. Enum Constants

The body of an enum declaration may contain enum constants. An enum constant defines an instance of the enum class.

In addition, constants aren't helpful if your subscribers can change after your code is compiled.

However, you can do any of the following:

  • Create and fill a set of subscribers, using java.util.Set<Subscriber> -- e.g., with a java.util.HashSet.
  • Make an enum of Subscriber types, and have each Subscriber hold a SubscriberType.
  • Create static final fields of type Subscriber. (This isn't helpful if your subscribers can change after compile-time.)
like image 79
Andy Thomas Avatar answered Sep 29 '22 06:09

Andy Thomas


The value in an enum class are always of the type of the enum. Though you can also add fields and methods to your enum class:

enum Subscriber{ subscriber1("s1"),subscriber2("s2"),subscriber3("s3"); 

 private final String name;
 private Subscriber(String n) {
    name = n;
 }
 
 public void greet() {
   System.out.println ("Hello" + name);
 }
}
like image 35
Jens Baitinger Avatar answered Sep 29 '22 06:09

Jens Baitinger