by Michael Morrison
Code reuse is one of the most significant benefits of using object-oriented design practices. Creating reusable, inheritable classes can save amazing amounts of time and energy-which in turn greatly boosts productivity. Java itself takes code reuse to heart in its implementation of a wide variety of standard objects available to Java programmers. The standard Java objects are known collectively as the Java standard packages.
The Java standard packages contain groups of related classes. Along with classes, the standard Java packages also include interfaces, exception definitions, and error definitions. Java is composed of six standard packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, and the applet package. In this chapter, you learn what each package is and what classes and interfaces comprise each.
The Java language package, also known as java.lang, provides classes that make up the core of the Java language. The language package contains classes at the lowest level of the Java standard packages. For example, the Object class, from which all classes are derived, is located in the language package.
It's impossible to write a Java program without dealing with at least a few of the elements of the language package. You'll learn much more about the inner workings of the language package in the next chapter. The most important classes contained in the language package follow:
The Object class is the superclass for all classes in Java. Because all classes are derived from Object, the methods defined in Object are shared by all classes. This results in a core set of methods that all Java classes are guaranteed to support. Object includes methods for making copies of an object, testing objects for equality, and converting the value of an object to a string.
The fundamental data types (int, char, float, and so on) in Java are not implemented as classes. It is frequently useful, however, to know more information about a fundamental type than just its value. By implementing class wrappers for the fundamental types, additional information can be maintained-you can also define methods that act on the types. The data type wrapper classes serve as class versions of the fundamental data types and are named similarly to the types they wrap. For example, the type wrapper for int is the Integer class. Following are the Java data type wrapper classes:
Type wrappers are also useful because many of Java's utility classes require classes as parameters, not simple types. It is worth pointing out that type wrappers and simple types are not interchangeable. However, you can get a simple type from a wrapper through a simple method call, which you learn about in the next chapter.
The Math class serves as a grouping of mathematical functions and constants. It is interesting to note that all the variables and methods in Math are static and that the Math class itself is final. This means that you can't derive new classes from Math. Additionally, you can't instantiate the Math class. It's best to think of the Math class as just a conglomeration of methods and constants for performing mathematical computations.
The Math class includes the E and PI constants, methods for determining the absolute value of a number, methods for calculating trigonometric functions, and minimum and maximum methods, among others.
For various reasons (mostly security related), Java implements text strings as classes, rather than forcing the programmer to use character arrays. The two Java classes that represent strings are String and StringBuffer. The String class is useful for working with constant strings that can't change in value or length. The StringBuffer class is used to work with strings of varying value and length.
The System and Runtime classes provide a means for your programs to access system and runtime environment resources. Like the Math class, the System class is final and is entirely composed of static variables and methods. The System class basically provides a system-independent programming interface to system resources. Examples of system resources include the standard input and output streams, System.in and System.out, which typically model the keyboard and monitor.
The Runtime class provides direct access to the runtime environment. An example of a runtime routine is the freeMemory() method, which returns the amount of free system memory available.
Java is a multithreaded environment and provides various classes for managing and working with threads. Following are the classes and interfaces used in conjunction with multithreaded programs:
Threads and multithreading are covered in detail in Chapter 9, "Threads and Multithreading."
Java provides two classes for working with classes: Class and ClassLoader. The Class class provides runtime information for a class, such as the name, type, and parent superclass. Class is useful for querying a class for runtime information, such as the class name. The ClassLoader class provides a means to load classes into the runtime environment. ClassLoader is useful for loading classes from a file or for loading distributed classes across a network connection.
Runtime error handling is a very important facility in any programming environment. Java provides the following classes for dealing with runtime errors:
Error handling with exceptions is covered in detail in Chapter 10, "Exception Handling."
Java supports system processes with a single class, Process. The Process class represents generic system processes that are created when you use the Runtime class to execute system commands.
The Java utilities package, also known as java.util, provides various classes that perform different utility functions. The utilities package includes a class for working with dates, a set of data structure classes, a class for generating random numbers, and a string tokenizer class, among others. You'll learn much more about the classes that make up the utilities package in Chapter 13, "The Utilities Package." The most important classes contained in the utilities package follow:
The Date class represents a calendar date and time in a system-independent fashion. The Date class provides methods for retrieving the current date and time as well as computing days of the week and month.
The Java data structure classes and interfaces implement popular data structures for storing data. The data structure classes and interfaces are as follows:
Many programs, especially programs that model the real world, require some degree of randomness. Java provides randomness with the Random class. The Random class implements a random-number generator by providing a stream of pseudo-random numbers. A slot-machine program is a good example of one that would make use of the Random class.
The StringTokenizer class provides a means of converting text strings into individual tokens. By specifying a set of delimiters, you can parse text strings into tokens using the StringTokenizer class. String tokenization is useful in a wide variety of programs, from compilers to text-based adventure games.
The model-view paradigm is becoming increasingly popular in object-oriented programming. This model divides a program into data and views on the data. Java supports this model with the Observable class and the Observer interface. The Observable class is subclassed to define the observable data in a program. This data is then connected to one or more observer classes. The observer classes are implementations of the Observer interface. When an Observable object changes state, it notifies all its observers of the change.
The Java I/O package, also known as java.io, provides classes with support for reading and writing data to and from different input and output devices-including files. The I/O package includes classes for inputting streams of data, outputting streams of data, working with files, and tokenizing streams of data. You'll learn a lot more about the classes that make up the I/O package in Chapter 14, "The I/O Package." The most important classes contained in the I/O package follow:
Java uses input streams to handle reading data from an input source. An input source can be a file, a string, memory, or anything else that contains data. The input stream classes follow:
The InputStream class is an abstract class that serves as the base class for all input streams. The InputStream class defines an interface for reading streamed bytes of data, finding out the number of bytes available for reading, and moving the stream position pointer, among other things. All the other input streams provide support for reading data from different types of input devices.
Output streams are the counterpart to input streams; they handle writing data to an output source. Similar to input sources, output sources include files, strings, memory, and anything else that can contain data. The output stream classes defined in java.io follow:
The OutputStream class is an abstract class that serves as the base class for all output streams. OutputStream defines an interface for writing streamed bytes of data to an output source. All the other output streams provide support for writing data to different output devices. Data written by an output stream is formatted to be read by an input stream.
Files are the most widely used method of data storage in computer systems. Java supports files with two different classes: File and RandomAccessFile. The File class provides an abstraction for files that takes into account system-dependent features. The File class keeps up with information about a file including the location where it is stored and how it can be accessed. The File class has no methods for reading and writing data to and from a file; it is useful only for querying and modifying the attributes of a file. In actuality, you can think of the File class data as representing a filename, and the class methods as representing operating system commands that act on filenames.
The RandomAccessFile class provides a variety of methods for reading and writing data to and from a file. RandomAccessFile contains many different methods for reading and writing different types of information, namely the data type wrappers.
The StreamTokenizer class provides the functionality for converting an input stream of data into a stream of tokens. StreamTokenizer provides a set of methods for defining the lexical syntax of tokens. Stream tokenization can be useful in parsing streams of textual data.
The Java networking package, also known as java.net, contains classes that allow you to perform a wide range of network communications. The networking package includes specific support for URLs, TCP sockets, IP addresses, and UDP sockets. The Java networking classes make it easy and straightforward to implement client/server Internet solutions in Java. You learn much more about the classes that make up the networking package in Chapter 15, "The Networking Package." The classes included in the networking package follow:
The InetAddress class models an Internet IP address and provides methods for getting information about the address. For example, InetAddress contains methods for retrieving either the text name or raw IP representation of the host represented by the address. InetAddress also contains static methods that allow you to find out about hosts without actually creating an InetAddress object.
The URL classes are used to represent and interact with Uniform Resource Locators (URLs), which are references to information on the Web. Following are the URL classes included in the networking package:
The socket classes are perhaps the most important classes contained in the networking package. They provide the entire framework for performing network communication through a couple of different approaches. The classes that comprise Java's socket support follow:
The ContentHandler class serves as a framework for handling different Internet data types. For example, you can write a content handler to process and display a proprietary file format. To do this, you would derive a class from ContentHandler and write code to build an object from a stream of data representing the object type.
The Java windowing package, also known as java.awt, consists of classes that provide a wide range of graphics and user interface features. This package includes classes representing graphical interface elements such as windows, dialog boxes, menus, buttons, checkboxes, scroll bars, and text fields, as well as general graphics elements such as fonts. You learn much more about the classes in the windowing package in Chapter 16, "The Windowing (AWT) Package." The most important classes included in the windowing package follow:
Note |
The windowing package is also often referred to as the Abstract Windowing Toolkit (AWT), which is where the name java.awt comes from. |
The graphical classes are all based on serving a particular graphical
user input or display need. For this reason, the graphical classes
are often indispensable in applet programming. The graphical classes
include support for everything from checkboxes and menus to canvases
and color representations.
Note |
Although I mention the graphical classes here only in terms of Java applets, these classes are equally useful in graphical standalone Java applications. Just keep in mind that standalone applications must create their own frame window to house any graphical elements; applets can simply use the applet window that has been allotted on the containing Web page. |
One of the most important GUI classes is the Graphics class, which serves as an all-purpose graphical output class capable of performing all kinds of different drawing functions. The Graphics class is ultimately responsible for all graphical output generated by a Java applet.
The Component class is another very fundamental graphical class and serves as the parent for many of the other graphical classes. It is used this way primarily because Component provides all the overhead necessary for a basic graphical element.
The layout manager classes provide a framework for controlling the physical layout of GUI elements. For example, you may want to have a row of buttons arranged in a certain way across the top of an applet window. You would use a layout manager to accomplish this. Following are the layout manager classes implemented in the windowing package:
All the layout classes are derived from the LayoutManager interface, which defines the core functionality required of a graphical layout manager.
The font classes consist of the Font class and the FontMetrics class. The Font class represents graphical font objects with attributes such as name, size, and style. Furthermore, Font objects can also be made bold or italic. The FontMetrics class provides a means to find information about the size of a font. For example, you can use a FontMetrics object to ascertain the height of a font, or something more specific such as a font's line spacing (leading).
The dimension classes provide a convenient way to represent different graphical dimensions in Java. The following dimension classes are defined in the windowing package:
The MediaTracker class provides a means to track when media resources have finished transmitting across a network connection. Currently, the MediaTracker class supports only the tracking of images, but a future release of Java will no doubt add support for sounds and other media types as they gain popularity. The MediaTracker class serves a very useful purpose for applets because it allows them to know when a particular image is ready to be displayed. For some applets, this knowledge is critical.
The Java applet package, also known as java.applet, contains only one class: Applet. The Applet class contains all the overhead required of a Java applet-which is quite a lot. The Applet class includes methods for accessing applet parameters, loading images, and playing sounds, along with plenty of general behind-the-scenes applet support. One other interesting component of the applet package is the AudioClip interface, which defines the basic functionality required of a Java audio clip.
This chapter provided a thumbnail sketch of the contents of the six Java standard packages: the language package, the utilities package, the I/O package, the networking package, the windowing package, and the applet package. Although you didn't learn a lot of gritty details, or how to use any of these classes in a real program, you should now have a general sense of what these packages can do. The Java standard packages provide a rich set of classes for overcoming a wide variety of programming obstacles.
A common problem when using programming environments that have a lot of support libraries is knowing what functionality is provided and what functionality you must write yourself. This chapter has given you an idea of what standard classes you can reuse in your own Java programs, and what classes you will have to implement yourself.
Having seen what each package in the Java standard packages contains, you're probably eager to start learning how to use the classes in each package. The next six chapters focus on the packages that make up the Java standard packages.