Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet130/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   126   127   128   129   130   131   132   133   ...   245
Bog'liq
Java 17 Recipes

 How It Works
A common pattern for representing a fixed set of related constants is defining each 
constant as an int, string, or other data type. Often, these constants are defined in a class 
or interface whose sole purpose is to encapsulate constants. In any case, constants are 
sometimes defined with the static and final modifiers, as follows.
// Input field constants
public static final int PASSWORD = 0;
public static final int EMAIL_ADDRESS = 1;
public static final int PHONE_NUMBER = 2;
public static final int SOCIAL_SECURITY_NUMBER = 3;
There are multiple problems with this pattern, the primary issue being the lack of 
type safety. By defining these constants as ints, it is possible to assign an invalid value to 
a variable that is supposed to be allowed to hold only one of the constant values.
int inputField = PHONE_NUMBER; // OK
inputField = 4; // Bad - no input field constant with value 4;
compiles without error
Chapter 7 Data SourCeS anD ColleCtionS


242
As you can see, there is no compiler error or warning produced to inform you of 
this invalid value assignment. Chances are, you discover this at runtime when your 
application tries to use inputField, and an incorrect value is assigned to it. In contrast, 
Java enum types provide compile-time type safety. That is, if one attempts to assign a 
value of the wrong type to an enum variable, it results in a compiler error. In the solution 
for this recipe, the FieldType.EMAIL_ADDRESS enum constant is assigned to the field 
variable. Attempting to assign a value that isn’t of type FieldType naturally results in a 
compiler error.
FieldType field = FieldType.EMAIL_ADDRESS; // OK
field = "EMAIL_ADDRESS"; // Wrong type - compiler error
An enum is simply a special type of class. Under the covers, Java implements an 
enum type as a subclass of the abstract and final java.lang.Enum class. Thus, an 
enum type cannot be instantiated directly (outside of the enum type) or extended. The 
constants defined by an enum type are instances of it. The java.lang.Enum class defines 
several final methods that all enum types inherit. In addition, all enum types have two 
implicitly declared static methods: values() and valueOf(String). The solution code 
demonstrates these static methods and some of the more often used instance methods.
Most of these methods are self-explanatory, but you should keep the following 
in mind.
• Each enum constant has an ordinal value representing its relative 
position in the enum declaration. The first constant in the declaration 
is assigned an ordinal value of zero. The ordinal() method can 
retrieve an enum constant’s ordinal value; however, it is not 
recommended that applications be written to depend on this value 
for maintainability reasons.
• The name() method and the default implementation of the 
toString() method both return a string representation of the 
enum constant (toString() actually calls name()). It is common 
for toString() to be overridden to provide a more user-friendly 
string representation of the enum constant. For this reason, and for 
maintainability reasons, it is recommended that toString() be used 
in preference to name().
Chapter 7 Data SourCeS anD ColleCtionS


243
• When testing for equality, note that both the equals() method 
and == perform reference comparison. They can be used 
interchangeably. However, it is recommended that == take advantage 
of compile-time type safety. This is illustrated in the solution code. 
Performing equals() comparison with a string parameter, for 
example, may allow the error to go unnoticed; it compiles, but it 
always returns false. Conversely, comparing an enum with a string 
using the == comparison would result in an error at compile time. 
When you choose to catch errors sooner (at compile time) rather 
than later (at runtime), choose the former.
• The implicitly declared values() and valueOf(String) static 
methods do not appear in the Java documentation or the source 
code for the java.lang.Enum class. However, the Java Language 
Specification does detail their required implementations. To 
summarize these methods, values() returns an array containing 
the constants of the enum in the order they are declared. The 
valueOf(String) method returns the enum constant whose name 
matches (including case) the value of the string argument or throws 
IllegalArgumentException if there is no enum constant with the 
specified name.
Refer to Java documentation (
https://docs.oracle.com/en/java/javase/17/
docs/api/java.base/java/lang/Enum.html
) for more information on java.lang.Enum 
and each of its methods. As the next recipe demonstrates, enum types, as full-fledged 
Java classes, can build more intelligent constants.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   126   127   128   129   130   131   132   133   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling