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
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:
java.util.Set<Subscriber>
-- e.g., with a java.util.HashSet
.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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With