When should we use an enum over a regular constant variable? - java

An enum is a specialized class that holds a set of constants. If we wanted to declare a field (variable) to be a constant in Java, we would use the keyword final. When should we use an enum over a regular constant variable?

Advantage of enum: type-safety
For example, considering the months, if we have constants as int (static final int JANUARY = 1)1 then a variable or method parameter must be declared as int and would accept any integer value , valid or not(e.g. setMonth(123) or setMonth(0)).
If we have an enum, then the variables or method parameters can only accept its values - errors (wrong constants) can be detected at compile time (exception: null which can also be assigned/passed instead of an enum, like any reference type).
1: not the same definition as from Calendar (JANUARY = 0)
Official Oracle tutorial Enum Types:
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Enums are typically used for groups of constants that are related. For example, shirt_sizes may be an enum of Small, Medium, Large, X-Large and so on. These will always be the same and we know what they are at the time we write the program.
If you want further reading that helps to explain why we use enums, check out this article https://crunchify.com/why-and-for-what-should-i-use-enum-java-enum-examples/

Related

Difference of enum in C and Java

I would like to know what is the difference of Enum between C and Java. And is there a way to "translate" a C enum into a Java enum ?
That's because I have an enum written in C on a robot containing types messages and I need to have the same in Java so that it could read data i send from an app.
In C, an enumeration is just a set of named, integral constants. In Java, an enumeration is more like a named instance of a class. You have the ability to customize the members available on the enumeration.
Also, C will implicitly convert enum values to their integral equivalent, whereas the conversion must be explicit in Java.
For More Information Visit:
Enum In C & Enum In Java
Java Enum is different from C Enum, because in Java Enum is a kind of class, when C\C++ enums is constant, that can be used in indexed expressions and as operands. Also, C\C++ enumerations provide an alternative to the #define preprocessor directive.
P.S.: To get more information, read Effective Java (http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683) 6th chapter (item 30-37) about it, the usage and the differences with C\C++ enums.
Opposed to C, which uses enum as a set of named constants, Java implements it as a class. And if you are concerned about performance do not use it in Android (The Price of enums).

Coding conventions: final class instance in CAPITAL_LETTERS?

Constants (final) of primitive types should be written in CAPITAL_LETTERS. But what about a class instance? For example, when it is passed as a function parameter, is called from inner class and should be declared final. Are all parameters supposed to be final? Should it be this way then:
public static void myFunction(
final MyClass CLASS_INSTANCE) {
// Code.
}
CAPITAL_LETTERS... What about a class instance?
Nope. That would be weird. Parameters use camel case. The fact that something is final doesn't affect conventions around case.
Are all parameters supposed to be final?
No. Declare things final if they shouldn't ever change. That often applies to a parameter, but not always.
Declaring something final does two things: it helps pick up bugs where something never gets initialised or can be changed after initialisation; and it acts as a hint to the compiler to allow some optimisations.
No, final parameters should not be written in all-uppercase -- they're not constants.
The terms constant and final are not synonymous.
Uppercase is indeed used for constants, as specified by early Java naming conventions.
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_").
But not all variables declared final are constants. From the Java language specification, section 4.12.4, "Final variables":
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).
Parameters are not constants. They're not initialized with a constant expression. And in your example, the parameter is not a primitive type or String.
Therefore, parameters are specified in mixed case, with an initial lowercase first letter.
To start with a nitpick: Java does not really have constants. It has final static variables, which -- for all intents and purposes -- often behave like constants. But they behave differently (and unexpectedly) in some rare situations, even when they have a primitive type.
Anyway, by convention, variables which behave like constants are given name in capitals. For example, java.awt.Color defines constants RED and BLUE of type Color. (It also defines constants red and blue, but since RED and BLUE were added later, I suspect the Sun/Oracle people considered those names a mistake.)
But parameters are not constants and do not behave like them. For every method invocation they can have a different value. Thus parameters are always named in camel case, even if they are declared final.
And should parameters be declared final? When, here is where convention stops and mere taste begins. Some people say yes, some people say no. I belong to the "no" camp. Making a parameter final could help prevent introducing bugs by giving a compiler error if you try to modify it. However, if your method body is so long that you actually require this help, then your method should probably be refactored. On the other side, I find parameter lists without final keywords everywhere easier to read and clearer, so I tend to leave them out.

What is difference between Fields and Constants in android documentations?

What is difference between Fields and Constants in android documentations?
For example in View Class we have Fields and Constants.Whiles, I think that the Constants in View Class are Fields. Because each variable in each class is Field. Please example for me about this ambiguity.
When your app is compiled, any constant values are compiled directly into the application. Using an example from #CommonsWare's comment, ACCESSIBILITY_LIVE_REGION_ASSERTIVE is an integer with the value 2. That value will continue to be used by your app even if the View class is updated in a future release of Android, which is why you can't put "what version of Android am I currently running on" in a constant. Conversely, it's a fine way to record which version of the SDK your app was compiled against.
The fields are final, which means you can't change them, unless you use JNI, in which case you can. However, because the compiler uses the values directly whenever possible, changing the value of the final fields won't affect any code -- unless it accesses them through reflection.
So the distinction between "constant" and "field" may be of importance.
Primitive types and Strings may be constants. For arrays and other object types, such as the int[] used for SELECTED_STATE_SET, the reference itself is read-only, but the contents of the object are not. This is true of any mutable object type, so it doesn't make sense to list them under "constants".
There is no such thing as a Constant in Java. There are only fields which you can mark static to became a class field (i.e. one instance per class, for all objects of the same class, rather than one per each object, as if without "static"). You can access static fields by class name reference, without instantiating the class (i.e. MyClassName.sMyStaticField)
Furthermore, you can mark your field final. That means the field value assigned in initialization code and will never change. If you are assigning to static final field a constant value (for example, a number), this value will be unchanged and the same for all class instances. So, in Java it is used as a constant value, to assign a particular value to a particular name.
Since their values are known at a compile time, they can be used to make conditional compilation. Part of your code, depending on such constant values, could be excluded at a compile time
public static final boolean ENABLE_MY_SUPER_DUPER = false;
...
if (ENABLE_MY_SUPER_DUPER) {
doSuperDuper(); // Not just never executed, but not even compiled
}
That's cannot be happened, if value assigned to a field could not be known at a runtime (for example, references to objects, or arrays)
So, technically, static final fields and so called "constants" is the same, but in documentation "constants" denotes some predefined constant values, that the same for all applications (i.e. numbers, string constants etc.).
While in "field" under "static final" there are some objects, which are instantiated once just after application starts, but it's value cannot be known at a compile time. For example, arrays, some object instances, etc.
Technically you cannot alter their values, since they are finals, but you can alter their internal content. I.e. you cannot create new object or array and assign it to the same field, but you can alter items or fields of already created array/object.
Had same doubt though got the correct answer. In ViewGroup.LayoutParams class there are three constants and three fields
Constants :
int WRAP_CONTENT
int FILL_PARENT
int MATCH_CONTENT
Fields :
public int height
public layoutAnimationParameters
public int width
the difference can be seen in the source code of android
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/ViewGroup.java#7857
here we see
public static final int FILL_PARENT = -1;
so the constants are nothing but fields which are final
Hope this helps!!

Can the methods in an Enum type change the state of the instances of an Enum?

If Enums are an answer for getting rid of compile time constants , why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums ? Those methods can never change the state of the Enum instances or can they ? If they are allowed to change the state , then the invariant of an Enum type ie some type that exports a few constants will break IMHO.
Java enums are really just classes with some special treatment by the compiler and runtime. So yes, method calls on an enum instance can certainly change its state. I'm not sure what you mean with "then the invariant of an Enum type ie some type that exports a few constants will break".
Who says enums can only be a bunch of constants? The essence of an enum type is that you have a predefined fixed number of instances which you can refer to by name - and Java enums implement that. But why would a language not be allowed to have enums that are more powerful than that?
If you don't want the extra power, nobody forces you to use it. You can have Java enums without fields or methods, and they'll behave pretty much exactly like C enums.
Enums are compile-time constants, but their members aren't. It's usually not a good idea to change enum members at runtime, but it is possible. For this reason, you can't use an enum's members where compile-time constants are called for (e.g. in annotation parameters).
Hardly anything in Java is really a constant when you go try hard to mess things up. E.g. a String constant contains a char array. Arrays are not immutable. Here's an example of the mess you can make using inlined String constants:
public static void main(final String[] args) throws Exception {
final Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
System.arraycopy("frog".toCharArray(), 0,
(char[]) valueField.get(Boolean.TRUE.toString()), 0, 4);
System.out.println(Boolean.parseBoolean("frog")); // true
System.out.println(Boolean.parseBoolean("true")); // false
}
So, Java constants in most cases are just constants as long as your application is well-behaved.
why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums
Reasons are to allow replacing switch-statements with polymorphism and generally make programs more Object Oriented by allowing to define methods on the data.
Search for "type-safe enum pattern". Java Enums are an implementation of this design pattern on language level.

Enum in Java. Advantages?

What are some advantages of making enum in Java similar to a class, rather than just a collection of constants as in C/C++?
You get free compile time checking of valid values. Using
public static int OPTION_ONE = 0;
public static int OPTION_TWO = 1;
does not ensure
void selectOption(int option) {
...
}
will only accept 0 or 1 as a parameter value. Using an enum, that is guaranteed. Moreover, this leads to more self documenting code, because you can use code completion to see all enum values.
Type safety is one reason.
Another, that I find more important, is that you can attach metadata to enum values in Java. For example, you could use an enum to define the set of legal operations for a webservice, and then attach metadata for the type of request and data class:
AddItem(HttpMethod.POST, ProductEntry.class),
Java 5 enums originated from a typesafe enum pattern from Joshua Bloch's Effective Java (the first edition) to avoid the pitfalls of enums in C/C++/C# (which are simply thinly-veiled int constants) and the use in Java of final static int constants.
Primarily int constants and int enums aren't typesafe. You can pass in any int value. In C/C++ you can do this:
enum A { one, two, three };
enum B { beef, chicken, pork } b = beef;
void func(A a) { ... }
func((A)b);
Unfortunately the typesafe enum pattern from Effective Java had a lot of boilerplate, not all of it obvious. The most notable is you had to override the private method readResolve to stop Java creating new instances on deserialization, which would break simple reference checking (ie using the == operator instead of equals()).
So Java 5 enums offer these advantages over ints:
Type safety;
Java 5 enums can have behaviour and implement interfaces;
Java 5 enums have some extremely lightweight data structures like EnumSet and EnumMap.
Java 5 enums over these advantages over just using classes:
Less error-prone boilerplate (private constructor, readResolve() etc);
Semantic correctness. You see something is an enum and you know it's just representing a value. You see a class and you're not sure. Maybe there's a static factory method somewhere, etc. Java 5 enums much more clearly indicate intent.
Enums are already a class in Java.
If you're asking why this is better, I'd say that better type safety and the ability to add other attributes besides a mere ordinal value would come to mind.
In addition to better type safety, you can also define custom behavior in your enums (refer to Effective Java for some good examples).
You can use enums to effectively implement Singletons ^^:
public enum Elvis {
INSTANCE
}
Making enum a reference type that can contain fixed set of constants has led to efficient Map implementation like EnumMap and Set implementation like EnumSet (JDK classes).
From javadoc of EnumMap :
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.
EnumMap combines richness and type safety of Map with the speed of an array (Effective Java).
Enums are a type in itself - you cannot use an enum that does not exist, or put in some other similar looking constant. and also, you can enumerate them, so that code can be more concise.
using static constants could potentially cause maintenence nightmares - especially if they area spread out.
The only real advantage is that it can be used in a switch statement. All the other stuff an enum is capable of can just be done with plain vanilla class with a private constructor whose instances in turn are declared as public static final fields of the class in question (the typesafe pattern). The other advantage of enum is obviously that it makes the code less verbose than you would do with a plain vanilla class.
But if I'm not mistaken, in C++ (or was it C#?) you can use a String in a switch statement. So that advantage of enums in Java is negligible as opposed to C++. However, same thing was proposed for Java 7, not sure if it will make it.
Benefits of Using Enumerations:
An object can be created to work in the same manner as an enumeration. In fact,
enumerations were not even included in the Java language until version 5.0. However,
enumerations make code more readable and provide less room for programmer error.
OCA Java SE 7 Programmer I Study Guide

Categories

Resources