Download Java, A Beginner`s Guide - Chapter 12

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java, A Beginner's Guide
Fifth Edition
by Herbert Schildt
Chapter 12
Chapter 12 covers Enumerations, Autoboxing, Static Import and Annotations. Enumerations
provide a way to define a subset of values for a particular object. Autoboxing provides a way to
transition between primitive types and their wrapper class and back. Static imports allow you
import static members of a class into your class. Annotations allow supplemental information to
be added to an object.
Enumerations
Enumerators contain a list of constant values that apply to a certain type of data, or object. They
can be useful in setting a scope of values for a particular object.
Enumeration Fundamentals
Syntax
enum enumName {
constants
}
Above is the general syntax of an enumeration in Java. Where enunName is a valid Java
identifier and constants are a list of comma separated constant values that the
enumeration contains.
Example
enum WeekDay {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY;
}
The above is an example for an enumeration of the days of the week. Notice that all
days are in all capitalized letters, this is not required but it is the commonly accepted way
to name constants.
Pages 408 and 409 in the book have code examples.
Java Enumerations Are Class Types
One of the key attributes of enumerations in Java is that they are classes. Enumerations in Java
can have methods, members and constructors just as any other class can have, which isn't the
case in many other languages. This attribute gives enumerations a little more power in Java.
The values( ) and valueOf( ) Methods
There are two methods defined for every enumeration in Java, values( ) and valueOf( ). The
values( ) method returns an array of all constants in an enumeration. The valueOf( ) method
takes a single parameter of the constant name to retrieve and returns the constant from the
enumeration, if it exists.
Example
WeekDays allWeekDays[] = WeekDays.values();
for (WeekDays wd : allWeekDays)
System.out.println(wd);
The above example uses the values( ) method to return an array of constants from the
WeekDays enumeration we defined earlier. The for loop then iterates these constants and prints
out each one to the console.
Example
WeekDays wd = WeekDays.valueOf("MONDAY");
System.out.println(wd);
The above example retrieves the constant named MONDAY from the WeekDays enumeration we
defined earlier and then prints it to the console.
Constructors, Methods, Instance Variables, and Enumerations
As mentioned earlier, enumerations in Java are also classes. Since they are classes, you can
define constructors, methods and instance variables.
Syntax
enum enumName {
constantOne(parameter-list), constantTwo(parameter-list), …,
constantN(parameter-list);
data-type variableName;
enumName (parameter-list) {
statements;
}
}
Above is the general syntax for defining an enumeration with constructors with constructors,
methods and instance variables. You'll notice in the constants list from the enumeration general
syntax above there has been a parameter-list added to each constant, these will be passed to the
matching constructor for that enumeration. Next you have the syntax for an instance variable,
which is the same as any other class. You have the data-type which defines the class or primitive
type for the variable and then the variableName, which is any value Java identifier. Finally we
have the constructor, with the enumName and parameter-list like any other constructor. You will
build this constructor, or these if there are multiple, to match the parameter-list(s) you have with
your constants.
Pages 411 and 412 in the book have a code example.
Two Important Restrictions
An enumeration cannot inherit another class and an enum cannot be a superclass.
Enumerations Inherit Enum
All enumerations in Java inherit the Enum class, java.lang.Enum, which provide a set of methods
for all enumerations. The two mentioned here are ordinal( ) and compareTo( ).
Example
WeekDays wd = WeekDays.MONDAY;
System.out.println(wd.ordinal());
The above example gets the constant for MONDAY from our WeekDays enumeration. We then
print the ordinal value to the console, which would be 1 in this case. The ordinal value provides
the order of the constant in the enumeration, starting with 0. So for our WeekDays enumeration,
Sunday would be 0 and Saturday would be 6.
Example
WeekDays wd1 = WeekDays.MONDAY;
WeekDays wd2 = WeekDays.MONDAY;
WeekDays wd3 = WeekDays.TUESDAY;
System.out.println(wd1.compareTo(wd2));
System.out.println(wd1.compareTo(wd3));
The above example gets three constants from the WeekDays enumeration. The first two, wd1
and wd2, are both MONDAY. The third one, wd3, is TUESDAY. We would then print out the
value of the compareTo( ) method for wd1 against wd2, which is 0 since they are the same, and
then the output of compareTo( ) method for wd1 against wd3, which would be -1 since MONDAY
is 1 position behind TUESDAY.
Page 414 has an example of these two methods.
A Computer-Controlled Traffic Light
An exercise using enumerations to create a traffic light simulation.
Autoboxing
Autoboxing and auto-unboxing were introduced in Java 5 to provide an easy way to convert from
a primitive to object and object to primitive. These two features work in conjunction with the type
wrappers we learned about earlier in the book, the int primitive type can be autoboxed into an
Integer class and the Integer class can be autounboxed into the primitive int on the fly by the
JVM.
Type Wrappers
Type wrappers are object representation of the primitive types in Java. In general, the primitive
types should be used unless it is necessary to have an object representation of their value, the
primitive types offer better performance. However, there are times when an object representation
of a value is useful, you can copy object references to a value for example.
Page 421 lists the type wrappers, their methods for retrieving values and some common
constructors.
Prior to Java 5 you had to manually box and unbox these values, similar to the example below.
Example
Integer iObj = new Integer(100);
int i = iObj.intValue( );
One drawback here is having to know the methods and the data types in your code, since the int
type is compatible with Double, Float, ETC this can be a bit messy at times.
Autoboxing Fundamentals
With autoboxing, you do not have to provide constructors or methods to make the transition from
primitive to object.
Example
Integer iObj = 100;
int i = iObj;
The above example does the exact same thing as the example in the previous section. Note that
you do not have to know the method intValue( ) nor do you have to call a constructor.
Autoboxing and Methods
Just like autoboxing happens for assignment, the same happens for methods.
Example
int add (int a, int b) {
return a + b;
}
Integer a = 100;
Integer b = 100;
add(a,b);
The above example, perhaps over simplified, shows the idea of autoboxing in methods. Notice
that the method add( ) takes two inputs of the primitive type int. The call to the add( ) method at
the end passes to Integer types, Java will auto-unbox those Integers to int.
Autoboxing/Unboxing Occurs in Expressions
Java will also perform the autboxing tasks for expressions inside of your code.
Example
Integer a = 0;
a++;
The above example would take the Integer a and unbox it to an int, add 1 and then box it back up
into an Integer.
A Word of Warning
As stated at the beginning of the autoboxing section, the primitive types are there
because they perform better than objects. For small programs the object representation
of these types is OK, but at a large scale they could cause performance problems. Only
use the object versions of these when absolutely necessary.
Static Import
I believe in the study group session we were really talking about generic imports rather than static
imports. Static imports apply directly to static members of a class, which generally require full
name references within your code.
While the accompanying video is not exactly in line with the book here, the idea is the same. A
static import allows you to bring a member into local scope with your class, allowing you to call it
directly by the member name rather than the fully qualified package and member name.
Syntax
import static pacakgeName.memberName;
Above is the general syntax for a static import. The packageName will be the full hierarchical
name up until the member being imported, java.lang.Math for example. The memberName will
be the member to be imported, sqrt for example. The memberName can also be an asterisk (*)
to import all member under that package, or all immediate members.
Annotations (Metadata)
Annotations provide a way to add supplemental information into a source file. They have various
ranges of function, and the book simply introduces them in this chapter.
Syntax
@interface annotationName {
data-type memberName( );
}
Above is the general syntax for declaring an annotation. The @interface tells Java that an
annotation is being declared. The annotationName is a valid Java identifier that will name the
annotation. Within the annotation can be any number of members defined by the data-type,
defining the object or primitive type of that member, and the memberName which is a valid Java
identifier for the member name.
Example
@annotationName(memberName = memberValue)
method
Above is a generic example of using an annotation. The annotationName is the name of the
defined annotation. Within the parentheses can be any number of memberName and
memberValue pairs to defined the values of that annotation's members, where memberName is
the name of the member within the annotation and the memberValue is a valid value for that
member. There doesn't have to be any member's inside of an annotation, so the parentheses
could be empty. The method is a method declaration that the annotation will be applied to.
On page 431 there is a tbale of annotations defined by java.lang. There is also a code example
on page 432.