List Inheritance

I gave an ABC enumeration and a class test, and I need to call doSomething, but I cannot pass the ABC enum as a parameter.

enum ABC{ A,B,C; } Class Test{ public void doSomething(ABC abc) { //some work } } 

Here I want a DEF enumeration, which must have all of the ABC member, and it must also have an XYZ enumeration member (I want a DEF enumeration, which must contain members of two enumerations (ABC and XYZ)). An example like this.

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

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

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

I am fresh. Please provide me any help or suggestion. I will be grateful to you.

+5
source share
3 answers

Enums in Java is final , which means you cannot extend and enumerate (you cannot add more values ​​to an existing enumeration). In your case, ABC and DEF are completely different objects with simple, identical enumeration element names. This implies, for example, that ABC.A != DEF.A

There are many ways to deal with this, but none of them are perfect or simple. You must convince what is necessary in your particular case.

The first way to handle this is to create a common interface that 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 } } 

Another approach is to add generics to your class. Thus, you can create specific implementations that will support the specified enumeration:

 class GenericTest<E extends Enum<E>>{ public void doSomething(E enum){ } } class TestWhichAcceptsABC extends GenericTest<ABC>{} class TestWhichAcceptsDEF extends GenericTest<DEF>{} 

The third way is to create several methods, one for each enumeration that needs to be processed

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

See this thread for more ideas on how to solve enum inheritance.

+9
source

Despite the fact that you mentioned the same name, it does not matter in the enumeration. Example A in ABC is an instance of ABC. But A in DEF is an instance of DEF. So these are different. You can implement the interface in an enumeration.

 enum ABC implements X{ A,B,C; } public class Test{ public void doSomething(X x) { } } 

You will try it.

+1
source

You cannot extend enums, but you can do the next best by modeling the enumeration behavior. You can create a class with a static value. Like this.

 public class abc extends yxz { public static final int A = 1; public static final int B = 2; public static final int C = 3; } 
-2
source

Source: https://habr.com/ru/post/1209613/


All Articles