Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a enum in Java

Tags:

java

enums

I have an enum, let's call it A:

public enum A {     A,     B } 

I have a function that takes an enum A:

public void functionA(A enumA) {     //do something } 

How can I create another enum, possibly call B that I can pass to functionA? Something like this?

public enum B {     C }  functionA(B.C); 

I know that you can't extend an enum, but what other options do I have available? What is the best way to achieve this?

like image 526
user489041 Avatar asked Jun 28 '11 18:06

user489041


People also ask

Why we Cannot extend enum?

Enum and has several static members. Therefore enum cannot extend any other class or enum: there is no multiple inheritance. Class cannot extend enum as well. This limitation is enforced by compiler.

Can enum inherit Java?

Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.

How do I add value to an enum in Java?

You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s). The initialization should be done only once. Therefore, the constructor must be declared private or default. To returns the values of the constants using an instance method(getter).

Which class does all the enum extend?

Which class does all the Enums extend? Explanation: All enums implicitly extend java.


1 Answers

You can't.

Enum types are final by design.

The reason is that each enum type should have only the elements declared in the enum (as we can use them in a switch statement, for example), and this is not possible if you allow extending the type.

You might do something like this:

public interface MyInterface {     // add all methods needed here }  public enum A implements MyInterface {     A, B;     // implement the methods of MyInterface }  public enum B implements MyInterface {     C;     // implement the methods of MyInterface } 

Note that it is not possible to do a switch with this interface, then. (Or in general have a switch with an object which could come from more than one enum).

like image 67
Paŭlo Ebermann Avatar answered Oct 05 '22 20:10

Paŭlo Ebermann