Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an enum have abstract methods?

Can an enum have abstract methods? If so, what is the use, and give a scenario which will illustrate this usage.

like image 328
java_geek Avatar asked Sep 14 '11 09:09

java_geek


People also ask

Can enum be abstract in java?

Java Language Enums Enums with Abstract MethodsEnums can define abstract methods, which each enum member is required to implement. This allows for each enum member to define its own behaviour for a given operation, without having to switch on types in a method in the top-level definition.

Can enum implement abstract class?

Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java. lang. Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.

Can we have methods in enum?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Is enum abstract data type?

An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically used to define a set of possible values that don't otherwise have a numerical order.


2 Answers

Yes, but you may prefer enum which implements an interface, Look here. I think It looks much better. This is example for abstract method:

public enum Animal {     CAT {         public String makeNoise() { return "MEOW!"; }     },     DOG {         public String makeNoise() { return "WOOF!"; }     };      public abstract String makeNoise(); } 
like image 83
lukastymo Avatar answered Sep 28 '22 07:09

lukastymo


Yes, you can define abstract methods in an enum declaration if and only if all enum values have custom class bodies with implementations of those methods (i.e. no concrete enum value may be lacking an implementation).

public enum Foo {   BAR {     public void frobnicate() {       // do BAR stuff     }   },   BAZ {     public void frobnicate() {       // do BAZ stuff     }   };    public abstract void frobnicate(); } 
like image 41
Joachim Sauer Avatar answered Sep 28 '22 06:09

Joachim Sauer