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
CodePudding user response:
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);
}
}
CodePudding user response:
When you define an enum:
public enum Subscribers {
subscriber1,
subscriber2,
subscriber3;
}
It means you define (i.e. from the given snippet) 3 singleton objects of class Subscribers
. In other words, this is absolutely normal instances like others (e.g. new InputStream()
). And you are free to implement what you want in these classes.
public interface Subscribe {
void subscribe(Object obj);
}
public enum Subscribers implements Subscribe {
txtFileSubscriber {
private final InputStream in = new InputStream("foo.txt");
public void subscribe(Object obj) {
// implementtion
}
},
xmlFileSubscriber {
private final CsvReader reader = new CsvReader("foo.csv");
public void subscribe(Object obj) {
// implementtion
}
}
}
P.S. Given snippet is only to show how you can extend enum. This is very powerful feature.
CodePudding user response:
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 ajava.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.)