Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enums can have behavior?

Tags:

java

oop

enums

In Java, an Enum can do the great things that Enums do, but can also have methods (behavior and logic). What advantage does that have over using a class using an enum? Simple examples to illustrate the point would also be welcome.

like image 855
Dave Avatar asked Apr 07 '09 14:04

Dave


People also ask

Can Java enums have values?

Overview. The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.

Can enum have attributes Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.

Can enums have setters?

Update: It's possible to have setters in enum types. Save this answer.


2 Answers

Here's a simple example:

enum RoundingMode {
    UP {
        public double round(double d) {
            return Math.ceil(d);
        }
    },
    DOWN {
        public double round(double d) {
            return Math.floor(d);
        }
    };

    public abstract double round(double d);
}
like image 114
Adam Crume Avatar answered Sep 28 '22 10:09

Adam Crume


Enum types are also a great way to implement true singletons.

Classic singleton patterns in Java typically involve private constructors and public static factory methods but are still vulnerable to instantiation via reflection or (de-)serialization. An enum type guards against that.

like image 28
Steve Reed Avatar answered Sep 28 '22 10:09

Steve Reed