Java Enum Definition

Java Enum definition

It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:

public class StatusCode extends Enum<StatusCode>

Now if you check the constraints, we've got Enum<StatusCode> - so E=StatusCode. Let's check: does E extend Enum<StatusCode>? Yes! We're okay.

You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that Enum<E> implements Comparable<E>. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)

I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:

public interface IBuilder<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder>

public interface IMessage<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder>

This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.

EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the right case rather than protect you from the wrong case.

So if Enum weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types:

public class First extends Enum<First> {}
public class Second extends Enum<First> {}

Second would implement Comparable<First> rather than Comparable<Second>... but First itself would be fine.

Why would I use an Enum, and not just a class?

Enums are strictly limited. It is impossible to define an enum value outside of the specified values (whereas with a class you can invoke new to create a new value).

Enums are also heavily optimized by at least most JVMs, and there are also new classes and language features which take advantage of enums' compactness and speed. For example, there are new classes created, EnumSet and EnumMap, which implement an enum-keyed set or map using a bitset and an array, respectively (which are probably the fastest possible implementations for those abstract data types).

Additionally, enum types can be used in switch statements. If you're pre-Java1.7, this is your best option for customized switch statements (and is still probably superior to using String values because of type safety; mistyping the enum value will cause a compile-time error, but mistyping the string will cause a more insidious runtime error-- or worse, a logic error that you can't understand until you really stare at the code and see the typo).

Defining an enum of integer values in java

I'm not sure enum is the best choice here, but you could try something like:

public enum Pitch {
p60(60), p62(62), ...;

private final int pitch;

Pitch(int pitch) {
this.pitch = pitch;
}

public int getValue() {
return pitch;
}
}

Explain of a ENUM definition in JAVA

Enum

The enum declaration defines a class (called an enum type). The enum
class body can include methods and other fields. The compiler
automatically adds some special methods when it creates an enum.

enums are special type of class. Instead of creating singleton pattern using regular class or to create constants, like WeekDays, we can use enum in such places. Here

EXTRACT("Extraction", "EXTRACTED", "EXTRACTION_FAILED"), 

Here EXTRACT is an enum constant meaning it is an instance of the classProcessStage and also all other enum constants(ROUTE, PUBLISH). All costants of enum are unique objects, meaning they are singleton instance created in the jvm and enum makes sure the instances are unique. You need not to put additional effort to create singleton pattern.

The above code is not only declaration, it is also calling the constructor with three String parameters to create the instance.

  private ProcessStage(String detailedName, String successState, String failedState) {
this.detailedName = detailedName;
this.successState = successState;
this.failedState = failedState;
}

why there are a lot of methods defined inside it?

Since it is also a class, it can have methods like any other classes. But the restriction is, it cannot be inherited, because internally enum extens the class Enum<E extends Enum<E>> class.

how to use method with a enum variable?

EXTRACT.getFailedState() //returns "EXTRACTION_FAILED"

Should Java enums be defined in their own files?

You can make it public in the same class, only public class should be defined in a separate Java file.

public class Card {
// ...
public enum CARD_SUITE { HEARTS, DIAMONDS, CLUBS, SPADES; }
}

You can then access the enum like Card.CARD_SUITE.HEARTS, Card.CARD_SUITE.DIAMONDS...

What's the use of enum in Java?

Enum serves as a type of fixed number of constants and can be used at least for two things

constant

public enum Month {
JANUARY, FEBRUARY, ...
}

This is much better than creating a bunch of integer constants.

creating a singleton

public enum Singleton {
INSTANCE

// init
};

You can do quite interesting things with enums, look at here

Also look at the official documentation

Enums defined in a class is a static nested class?

The JLS says

An enum declaration specifies a new enum type, a special kind of class type.

So it looks like the word from Oracle is that enums are classes.

If you declare an enum inside another class, then yes, it's an inner class. And enums are always static, so yes, it's fair to call an enum a static inner class (or nested class) when it's declared in another class.

Java enum value fields not accessible outside of definition

As per JLS §8.9.1. Enum Constants an enum constant body is governed by the rules applicable to anonymous class, which restrict the accessibility of fields and methods:

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8).



Related Topics



Leave a reply



Submit