Extending the Enum Class
Enum's generic type is Enum lt E extends Enum lt E gt gt . Although the formal type parameter list looks ghastly, it is not that hard to understand. But first, take a look at Listing 5-42. Listing 5-42. The Coin class as it appears from the perspective of its classfile public final class Coin extends Enum lt Coin gt public static final Coin PENNY new Coin PENNY, 0 public static final Coin NICKEL new Coin NICKEL, 1 public static final Coin DIME new Coin DIME, 2 public static final Coin OUARTER...
Integer Long Short and Byte
Integer, Long, Short, and Byte store 32-bit, 64-bit, 16-bit, and 8-bit integer values in Integer, Long, Short, and Byte objects, respectively. Each class declares MAX_VALUE and MIN_VALUE constants that identify the maximum and minimum values that can be represented by its associated primitive type. These classes also declare the following constructors for initializing their objects Integer int value initializes the Integer object to value. Integer String s converts s's text to a 32-bit integer...
Resource Bundles
An internationalized application contains no hard-coded text or other locale-specific elements such as a specific currency format . Instead, each supported locale's version of these elements is stored outside of the application. NOTE Creating a set of locale-specific elements is known as localization. Java is responsible for storing each locale's version of certain elements, such as currency formats. In contrast, it is your responsibility to store each supported locale's version of other...
Summary Hlr
Java version 5 introduced the concurrency utilities to simplify the development of concurrent applications. The concurrency utilities are organized into executor, synchronizer, concurrent collection, lock, and atomic variable categories, and leverage the low-level Threading API in their implementations. An executor decouples task submission from task-execution mechanics and is described by the Executor, ExecutorService, and ScheduledExecutorService interfaces. A synchronizer facilitates common...
Using MetaAnnotations in Annotation Type Declarations
Each of the Override, Deprecated, and SuppressWarnings annotation types is itself annotated with meta-annotations annotations that annotate annotation types . For example, Listing 5-18 shows you that the SuppressWarnings annotation type is annotated with two meta-annotations. Listing 5-18. The annotated SuppressWarnings type declaration Retention value SOURCE The Target annotation type, which is located in the java.lang.annotation package, identifies the kinds of application elements to which...
Chapter 3 Learning ObjectOriented Language Features
1. Implementation inheritance is inheritance through class extension. 2. Java supports implementation inheritance by providing reserved word extends. 3. A subclass can have only one superclass because Java does not support multiple implementation inheritance. 4. You prevent a class from being subclassed by declaring the class final. 5. The answer is false the super call can only appear in a constructor. 6. If a superclass declares a constructor with one or more parameters, and if a subclass...
Object Serialization and Deserialization
Although you can use the data stream classes to stream primitive type values and String objects, you cannot use these classes to stream non-String objects. Instead, you must use object serialization and deserialization to stream objects of arbitrary types. Object serialization is a virtual machine mechanism for serializing object state into a stream of bytes. Its deserialization counterpart is a virtual machine mechanism for deserializing this state from a byte stream. NOTE An object's state...
Upcasting and Late Binding
Listing 3-9's Point class represents a point as an x-y pair. Because a circle in this example is an x-y pair denoting its center, and has a radius denoting its extent, you can extend Point with a Circle class that introduces a radius field. Check out Listing 3-18. Listing 3-18. A Circle class extending the Point class The fact that Circle is really a Point with a radius implies that you can treat a Circle instance as if it was a Point instance. Accomplish this task by assigning the Circle...
Generic Methods
A generic method is a static or non-static method with a type-generalized implementation. A formal type parameter list precedes the method's return type, uses the same syntax, and has the same meaning as the generic type's formal type parameter list. This syntax is expressed as follows lt formal_type_parameter_list gt return_type identifier parameter_list The collections framework provides many examples of generic methods. For example, the Collections class provides a public static lt T extends...
OutputStreamWriter and InputStreamReader
The concrete OutputStreamWriter class a Writer subclass is a bridge between an incoming sequence of characters and an outgoing stream of bytes. Characters written to this writer are encoded into bytes according to the default or specified character encoding. NOTE The default character encoding is accessible via the file.encoding system property. Each call to an OutputStreamWriter write method causes an encoder to be called on the given character s . The resulting bytes are accumulated in a...
Declaring and Using Your Own Generic Types
It is not difficult to declare your own generic types. In addition to specifying a formal type parameter list, your generic type specifies its type parameter s throughout its implementation. For example, Listing 5-24 declares a Oueue lt E gt generic type. Listing 5-24. Declaring and using a Oueue lt E gt generic type private E elements private int head, tail public Oueue int size elements E new Object size head 0 tail 0 if isFull insert should throw an exception when full. I did return not...
Processing Annotations
It is not enough to declare an annotation type and use that type to annotate source code. Unless you do something specific with those annotations, they remain dormant. One way to accomplish something specific is to write an application that processes the annotations. Listing 5-21's StubFinder application does just that. Listing 5-21. The StubFinder application public static void main String args throws Exception System.err.println usage java StubFinder classfile return Method methods...
ByteArrayOutputStream and ByteArrayInputStream
Byte arrays are occasionally useful as stream destinations and sources. The concrete ByteArrayOutputStream class lets you write a stream of bytes to a byte array the concrete ByteArrayInputStream class lets you read a stream of bytes from a byte array. ByteArrayOutputStream declares a pair of constructors. Each constructor creates a byte array output stream with an internal byte array a copy of this array can be returned by calling ByteArrayOutputStream's byte toByteArray method...
BufferedOutputStream and BufferedlnputStream
FileOutputStream and FilelnputStream have a performance problem. Each file output stream write method call and file input stream read method call results in a call to one of the underlying platform's native methods, and these native calls slow down I O. NOTE A native method is an underlying platform API function that Java connects to an application via the Java Native Interface JNI . Java supplies reserved word native to identify a native method. For example, the RandomAccessFile class declares...
Polymorphism
Polymorphism is the ability to change forms. Examples of polymorphism abound in nature. For example, water is naturally a liquid, but it changes to a solid when frozen, and it changes to a gas when heated to its boiling point. Java supports several kinds of polymorphism Coercion An operation serves multiple types through implicit type conversion. For example, division lets you divide an integer by another integer, or divide a floating-point value by another floating-point value. If one operand...
The Enum Alternative
Java version 5 introduced enums as a better alternative to traditional enumerated types. An enum is an enumerated type that is expressed via reserved word enum. Listing 5-36 uses enum to declare Listing 5-34's and 5-35's enumerated types. Listing 5-36. Improved enumerated types for coins and weekdays public enum Coin PENNY, NICKEL, DIME, QUARTER public enum Weekday SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY Despite their similarity to the int-based enumerated types found in...
Enhancing an Enum
You can add fields, constructors, and methods to an enum you can even have the enum implement interfaces. For example, Listing 5-38 adds a field, a constructor, and two methods to Coin to associate a denomination value with a Coin constant such as 1 for penny and 5 for nickel and convert pennies to the denomination. Listing 5-38. Enhancing the Coin enum PENNY l , NICKEL 5 , DIME 10 , 0UARTER 25 private final int denomValue oin int denomValue public int toDenomination int numPennies Listing...
Float and Double
Float and Double store floating-point and double precision floating-point values in Float and Double objects, respectively. These classes declare the following constants MAX_VALUE identifies the maximum value that can be represented as a float or double. MIN_VALUE identifies the minimum value that can be represented as a float or double. NaN represents 0.0F 0.0F as a float and 0.0 0.0 as a double. NEGATIVE_INFINITY represents -infinity as a float or double. POSITIVE_INFINITY represents infinity...
Reference and ReferenceQueue
The References API consists of five classes located in the java.lang.ref package. Central to this package are Reference and ReferenceQueue. Reference is the abstract superclass of this package's concrete SoftReference, WeakReference, and PhantomReference subclasses. ReferenceQueue is a concrete class whose instances describe queue data structures. When you associate a ReferenceQueue instance with a Reference subclass object Reference object, for short , the Reference object is added to the...
SoftReference
The SoftReference class describes a Reference object whose referent is softly reachable. In addition to inheriting Reference's methods and overriding get , this generic class provides the following constructors for initializing a SoftReference object SoftReference T r encapsulates r's reference. The SoftReference object behaves as a soft reference to r. No ReferenceOueue object is associated with this SoftReference object. SoftReference T r, ReferenceOueue lt super T gt q encapsulates r's...
RandomAccessFile
Files can be created and or opened for random access in which a mixture of write and read operations can occur until the file is closed. Java supports this random access by providing the concrete RandomAccessFile class. RandomAccessFile declares the following constructors RandomAccessFile File file, String mode creates and opens a new file if it does not exist, or opens an existing file. The file is identified by file's pathname and is created and or opened according to the mode that is...
Throwing Exceptions
Now that you have created an InvalidMediaFormatException class, you can declare the Media class and begin to code its convert method. The initial version of this method validates its arguments, and then verifies that the source file's media format agrees with the format implied by its file extension. Check out Listing 4-24. Listing 4-24. Throwing exceptions from the convert method public static void convert String srcName, String dstName throws InvalidMediaFormatException throw new...
Preferences API
Significant applications have preferences, which are configuration items. Examples include the location and size of the application's main window, and the locations and names of files that the application most recently accessed. Preferences are persisted to a file, to a database, or to some other storage mechanism so that they will be available to the application the next time it runs. The simplest approach to persisting preferences is to use the Properties API, which consists of the Properties...
The Road Goes Ever On
Although this book is finished from Apress's perspective, it is not finished from my perspective because the physical limitations of a paperback book prevented me from covering additional topics that are important to Android app developers networking is one example. Accordingly, I am writing six more chapters with the same organization as this book's chapters, but not necessarily with the same style that you will be able to freely download from my website javajeff.mb.ca as PDF files Chapter 11...
Installing and Exploring the JDK
The Java Runtime Environment JRE implements the Java SE platform and makes it possible to run Java programs. The public JRE can be downloaded from the Java SE Downloads page However, the public JRE does not make it possible to develop Java programs. For that task, you need to download and install the Java SE Development Kit JDK , which contains development tools including the Java compiler and a private JRE. NOTE JDK 1.0 was the first JDK to be released in May 1995 . Until JDK 6 arrived, JDK...
Jeff JavaJeff Friesen
Copyright 2010 by Jeff JavaJeff Friesen All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 pbk 978-1-4302-3156-1 ISBN-13 electronic 978-1-4302-3157-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names, logos, and...

















