Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in enum

I have given an enum ABC and a class Test and I have to call doSomething but I cannot pass ABC enum as parameter.

enum ABC{
   A,B,C;
 }

Class Test{

  public void doSomething(ABC abc)
  {
    //some work
   }

}

Here I want an enum DEF that should have all member of ABC and it should also have member of enum XYZ (I want an enum DEF that should contain members of two enums(ABC and XYZ)). Example like this.

 enum DEF 
 {
    A,B,C,X,Y,Z,D;
 }

 enum xyz{
     X,Y,Z;
 }

So that I can call doSomething method which takes only ABC enum as parameter. I want to call doSomething() method with DEF.Example

  class Demo{

     public static void main(String[] ags)
     {
         Test test= new Test();
         test.doSomething(DEF.A);
      }

 }

I am fresher. Kindly provide me any help or suggestion.I will be thankful to you.

like image 325
Anju Singh Avatar asked Dec 20 '14 16:12

Anju Singh


People also ask

Can enums have inheritance?

Inheritance Is Not Allowed for Enums.

Can enum be used as base class for inheritance?

Unfortunately, the traditional Enums being a value type do not support inheritance.

Can you inherit enum C++?

The Problem. C++ does not have a facility to allow one enum type to be extended by inheritance as it does for classes and structures.

Can we inherit enum in C#?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.


1 Answers

Enums in Java are final, which means you cannot extend and enum (you cannot add more values to existing enum). In you case the ABC and DEF are completely different entities with simple the same names of enum items. This implicates for example that ABC.A != DEF.A.

There are many ways to handle that, however none of them is perfect or simple. You should evaulate what is needed in your specific case.

First way to handle that is to create a common interface, which your enums can extend:

interface MyInterface{

}

enum ABC implements MyInterface{
   A,B,C;
 }

enum DEF implements MyInterface{ 
    A,B,C,X,Y,Z,D;

 }

This way you can use both ABC and DEF in doSomething():

Class Test{

  public void doSomething(MyInterface abc)
  {
    //some work
   }

 }

Other approach is to add generics to your class. This way you can create concrete implementations which will support specified enum:

class GenericTest<E extends Enum<E>>{
    public void doSomething(E enum){
    }
}

class TestWhichAcceptsABC extends GenericTest<ABC>{}

class TestWhichAcceptsDEF extends GenericTest<DEF>{}

Third way is to create multiple methods, one for each enum which need to be handled

Class Test{

   public void doSomething(ABC abc)
   {
    //some work
   }

   public void doSomething(DEF abc)
   {
    //some work
   }

}

See This thread for more ideas how to solve enum inheritance.

like image 125
Mariusz Jamro Avatar answered Sep 25 '22 01:09

Mariusz Jamro