1. Introduction

Objectives

In this chapter you’ll learn:

• Basic object technology concepts, such as classes, objects, attributes, behaviors, encapsulation, inheritance and polymorphism.

• A typical Java program development environment.

• Java’s role in developing distributed client/server applications for the Internet and the web.

• The history of UML—the industry-standard object-oriented design language, the UML.

• The history of the Internet and the web.

• To test-drive Java applications.

Our life is frittered away by detail.... Simplify, simplify.

Henry David Thoreau

The chief merit of language is clearness.

Galen

My object all sublime I shall achieve in time.

W. S. Gilbert

He had a wonderful talent for packing thought close, and rendering it portable.

Thomas B. Macaulay

“Egad, I think the interpreter is the hardest to be understood of the two!”

Richard Brinsley Sheridan

Man is still the most extraordinary computer of all.

John F. Kennedy

Outline

1.1   Introduction

1.2   The Internet and the World Wide Web

1.3   History of C and C++

1.4   History of Java

1.5   Java Class Libraries

1.6   Typical Java Development Environment

1.7   Notes about Java and Java for Programmers

1.8   Test-Driving a Java Application

1.9   Software Engineering Case Study: Introduction to Object Technology and the UML

1.10   Web 2.0

1.11   Software Technologies

1.12   Wrap-Up

1.13   Web Resources

1.1 Introduction

Welcome to Java! We have worked hard to create what we hope you’ll find to be an informative, entertaining and challenging professional experience. Java is one of today’s most popular and powerful software development languages and is appropriate for experienced programmers to use in building substantial information systems.

Pedagogy

The core of the book emphasizes achieving program clarity through the proven techniques of object-oriented programming. The presentation is clear, straightforward and abundantly illustrated. It includes hundreds of complete working Java programs and shows the outputs produced when those programs are run. We teach Java features in the context of complete working Java programs—we call this the live-code approach. The example programs can be downloaded from www.deitel.com/books/javafp/.

Fundamentals

The early chapters introduce the fundamentals of Java, providing a solid foundation for the deeper treatment in the later chapters. Experienced programmers tend to read the early chapters quickly and find the treatment of Java in the later chapters rigorous and challenging.

Java Standard Edition 6 (Java SE 6) and the Java Development Kit 6 (JDK 6)

This book is based on Sun’s Java Standard Edition 6 (Java SE 6). Sun provides a Java SE 6 implementation, called the Java Development Kit (JDK), that includes the tools you need to write software in Java. We used JDK version 6 for the programs in this book. Sun updates the JDK on a regular basis to fix bugs. To download the most recent version of JDK 6, visit java.sun.com/javase/downloads/index.jsp.

Object-Oriented Programming

The book focuses on object-oriented programming. Object orientation is the key programming methodology used by programmers today. You’ll create and work with many software objects in this text.

Language of Choice for Networked Applications

Java has become the language of choice for implementing Internet-based applications and software for devices that communicate over a network. Stereos and other devices in homes are now being networked together by Java technology. There are now billions of java-enabled computers, mobile phones and handheld devices! Java has evolved rapidly into the large-scale applications arena. It’s the preferred language for meeting many organizations’ enterprise programming needs.

Java has grown so large that it has two other editions. The Java Enterprise Edition (Java EE) is geared toward developing large-scale, distributed networking applications and web-based applications. The Java Micro Edition (Java ME) is geared toward developing applications for small, memory-constrained devices, such as cell phones, pagers and PDAs.

Staying in Touch with Us

If you would like to communicate with us, please send e-mail to [email protected]. We’ll respond promptly. To keep up to date with Java developments at Deitel & Associates, please register for our free e-mail newsletter, the Deitel® Buzz Online, at

www.deitel.com/newsletter/subscribe.html

For lots of additional Java material, visit our growing list of Java Resource centers at www.deitel.com/ResourceCenters.html.

1.2 The Internet and the World Wide Web

The Internet has its roots in the 1960s with funding supplied by the U.S. Department of Defense. Originally designed to connect the main computer systems of about a dozen universities and research organizations, the Internet is accessible by billions of computers and computer-controlled devices worldwide.

With the introduction of the World Wide Web—which allows computer users to locate and view multimedia-based documents on almost any subject over the Internet—the Internet has exploded into one of the world’s premier communication mechanisms.

The Internet and the web are surely among humankind’s most important and profound creations. In the past, most computer applications ran on computers that were not connected to one another. Today’s applications can be written to communicate among the world’s computers.

Java for Programmers presents programming techniques that allow Java applications to use the Internet and the web to interact with other applications. These capabilities and others allow Java programmers to develop the kind of enterprise-level distributed applications that are used in industry today. Java applications can be written to execute on every major type of computer, greatly reducing the time and cost of systems development. If you are interested in developing applications to run over the Internet and the web, learning Java may be the key to rewarding career opportunities for you.

1.3 History of C and C++

Java evolved from C++, which evolved from C, which evolved from BCPL and B. BCPL was developed in 1967 by Martin Richards as a language for writing operating systems software and compilers. Ken Thompson modeled many features in his B language after their counterparts in BCPL, using B to create early versions of the UNIX operating system at Bell Laboratories in 1970.

The C language was evolved from B by Dennis Ritchie at Bell Laboratories and was originally implemented in 1972. It initially became widely known as the development language of the UNIX operating system. Today, most of the code for general-purpose operating systems (e.g., those found in notebooks, desktops, workstations and small servers) is written in C or C++.

C++, an extension of C, was developed by Bjarne Stroustrup in the early 1980s at Bell Laboratories. C++ provides a number of features that “spruce up” the C language, but more important, it provides capabilities for object-oriented programming (discussed in more detail in Section 1.9 and throughout this book). C++ is a hybrid language—it is possible to program in either a C-like style, an object-oriented style or both.

Objects, or more precisely—as we’ll see in Section 1.9—the classes objects come from, are essentially reusable software components. There are date objects, time objects, audio objects, automobile objects, people objects and so on. In fact, almost any noun can be represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and communicating). Software developers now know that using a modular, object-oriented design and implementation approach can make software-development groups much more productive than was possible with earlier popular programming techniques like structured programming. Object-oriented programs are often easier to understand, correct and modify. Java is the world’s most widely used object-oriented programming language.

1.4 History of Java

Microprocessors are having a profound impact in intelligent consumer-electronic devices. Recognizing this, Sun Microsystems in 1991 funded an internal corporate research project code-named Green, which resulted in a C++-based language that its creator, James Gosling, called Oak after an oak tree outside his window at Sun. It was later discovered that there already was a computer language by that name. When a group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck.

The Green project ran into some difficulties. The marketplace for intelligent consumer-electronic devices was not developing in the early 1990s as quickly as Sun had anticipated. The project was in danger of being canceled. By sheer good fortune, the World Wide Web exploded in popularity in 1993, and Sun people saw the immediate potential of using Java to add dynamic content, such as interactivity and animations, to web pages. This breathed new life into the project.

Sun formally announced Java at an industry conference in May 1995. Java garnered the attention of the business community because of the phenomenal interest in the web. Java is now used to develop large-scale enterprise applications, to enhance the functionality of web servers, to provide applications for consumer devices (e.g., cell phones, pagers and personal digital assistants) and for many other purposes.

1.5 Java Class Libraries

Java programs consist of pieces called classes. Classes include pieces called methods that perform tasks and return information when they complete them. Programmers can create each piece they need to form Java programs. However, most Java programmers take advantage of the rich collections of existing classes in the Java class libraries, which are also known as the Java APIs (Application Programming Interfaces). Thus, there are really two aspects to learning the Java “world.” The first is the Java language itself, so that you can program your own classes, and the second is the classes in the extensive Java class libraries. Throughout this book, we discuss many library classes. Class libraries are provided primarily by compiler vendors, but many are supplied by independent software vendors (ISVs).

Software Engineering Observation 1.1

Image

Use a building-block approach to create programs. Avoid reinventing the wheel—use existing pieces wherever possible. This software reuse is a key benefit of object-oriented programming.

Software Engineering Observation 1.2

Image

When programming in Java, you’ll typically use the following building blocks: classes and methods from class libraries, classes and methods you create yourself and classes and methods that others create and make available to you.

The advantage of creating your own classes and methods is that you know exactly how they work and you can examine the Java code. The disadvantage is the time-consuming and potentially complex effort that is required.

Performance Tip 1.1

Image

Using Java API classes and methods instead of writing your own versions can improve program performance, because they are carefully written to perform efficiently. This technique also shortens program development time.

Portability Tip 1.1

Image

Using classes and methods from the Java API instead of writing your own improves program portability, because they are included in every Java implementation.

Software Engineering Observation 1.3

Image

Extensive class libraries of reusable software components are available over the Internet, many at no charge.

You can view the Java API documentation online at java.sun.com/javase/6/docs/ or download the documentation from java.sun.com/javase/6/download.jsp.

1.6 Typical Java Development Environment

We now explain the commonly used steps in creating and executing a Java application using a Java development environment (illustrated in Fig. 1.1).

Fig. 1.1. Typical Java development environment.

Image

Java programs normally go through five phases—edit, compile, load, verify and execute. We discuss these phases in the context of the JDK 6.0 from Sun Microsystems, Inc., You can download the most up-to-date JDK and its documentation from java.sun.com/javase/downloads/index.jsp. Carefully follow the installation instructions for the JDK provided in the Before You Begin section of this book (or at java.sun.com/javase/6/webnotes/install/index.html) to ensure that you set up your computer properly to compile and execute Java programs. [Note: This website provides installation instructions for Windows, Linux and Mac OS X. If you are not using one of these operating systems, refer to the manuals for your system’s Java environment or ask your instructor how to accomplish these tasks based on your computer’s operating system. In addition, please keep in mind that web links occasionally break as companies evolve their websites. If you encounter a problem with this link or any other links referenced in this book, please check www.deitel.com for errata and please notify us by e-mail at [email protected]. We’ll respond promptly.]

Phase 1: Creating a Program

Phase 1 consists of editing a file with an editor. You type a Java source code program using the editor, make any necessary corrections and save the program. A file name ending with the .java extension indicates that the file contains Java source code.

Two editors widely used on Linux systems are vi and emacs. On Windows, a simple editing program like Windows Notepad will suffice. Many freeware and shareware editors are also available for download from the Internet on sites like www.download.com.

For developing substantial information systems, integrated development environments (IDEs) are available from many major software suppliers, including Sun Microsystems. IDEs provide tools that support the software development process, including editors for writing and editing programs and debuggers for locating logic errors. Popular IDEs and editors include Eclipse (www.eclipse.org), NetBeans (www.netbeans.org), JBuilder (www.borland.com), JCreator (www.jcreator.com), BlueJ (www.blueJ.org), jGRASP (www.jgrasp.org) and jEdit (www.jedit.org). [Note: Most of our example programs should operate properly with any Java integrated development environment that supports the JDK 6.]

Phase 2: Compiling a Java Program into Bytecodes

In Phase 2, the programmer uses the command javac (invoking, the Java compiler) to compile a program. For example, to compile a program called Welcome.java, you would type

javac Welcome.java

in the command window of your system (i.e., the MS-DOS prompt in Windows 95/98/ME, the Command Prompt in Windows NT/2000/XP, the shell prompt in Linux or the Terminal application in Mac OS X). If the program compiles, the compiler produces a .class file called Welcome.class that contains the compiled version of the program.

The Java compiler translates Java source code into bytecodes that represent the tasks to execute in the execution phase (Phase 5). Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the Java platform. A virtual machine (VM) is a software application that simulates a computer, but hides the underlying operating system and hardware from the programs that interact with the VM. If the same VM is implemented on many computer platforms, applications that it executes can be used on all those platforms. The JVM is one of the most widely used virtual machines.

Unlike machine language, which is dependent on specific computer hardware, bytecodes are platform-independent instructions—they are not dependent on a particular hardware platform. So Java’s bytecodes are portable—that is, the same bytecodes can execute on any platform containing a JVM that understands the version of Java in which the bytecodes were compiled. The JVM is invoked by the java command. For example, to execute a Java application called Welcome, you would type the command

java Welcome

in a command window to invoke the JVM, which would then initiate the steps necessary to execute the application. This begins Phase 3.

Phase 3: Loading a Program into Memory

In Phase 3, the program must be placed in memory before it can execute. The class loader takes the .class files containing the program’s bytecodes and transfers them to primary memory. The class loader also loads any of the .class files provided by Java that your program uses. The .class files can be loaded from a disk on your system or over a network (e.g., your local college or company network, or the Internet).

Phase 4: Bytecode Verification

In Phase 4, as the classes are loaded, the bytecode verifier examines their bytecodes to ensure that they are valid and do not violate Java’s security restrictions. Java enforces strong security, to make sure that Java programs arriving over the network do not damage your files or your system (as computer viruses and worms might).

Phase 5: Execution

In Phase 5, the JVM executes the program’s bytecodes. In early Java versions, the JVM was simply an interpreter for Java bytecodes. This caused most Java programs to execute slowly because the JVM would interpret and execute one bytecode at a time. Today’s JVMs typically execute bytecodes using a combination of interpretation and so-called just-in-time (JIT) compilation. In this process, The JVM analyzes the bytecodes as they are interpreted, searching for hot spots—parts of the bytecodes that execute frequently. For these parts, a just-in-time (JIT) compiler—known as the Java HotSpot compiler—translates the bytecodes into the underlying computer’s machine language. When the JVM encounters these compiled parts again, the faster machine-language code executes. Thus Java programs actually go through two compilation phases—one in which source code is translated into bytecodes (for portability across JVMs on different computer platforms) and a second in which, during execution, the bytecodes are translated into machine language for the actual computer on which the program executes.

Problems That May Occur at Execution Time

Programs might not work on the first try. Each of the preceding phases can fail because of various errors that we’ll discuss throughout this book. For example, an executing program might try to divide by zero (an illegal operation for whole-number arithmetic in Java). This would cause the Java program to display an error message. If this occurs, you would have to return to the edit phase, make the necessary corrections and proceed through the remaining phases again to determine that the corrections fix the problem(s).

1.7 Notes about Java and Java for Programmers

You have heard that Java is a portable language and that programs written in Java can run on many different computers. In general, portability is an elusive goal.

Portability Tip 1.2

Image

Although it is easier to write portable programs in Java than in most other programming languages, differences between compilers, JVMs and computers can make portability difficult to achieve. Simply writing programs in Java does not guarantee portability.

Error-Prevention Tip 1.1

Image

Always test your Java programs on all systems on which you intend to run them, to ensure that they will work correctly for their intended audiences.

We audited our presentation against Sun’s Java documentation for completeness and accuracy. A web-based version of the Java API documentation can be found at java.sun.com/javase/6/docs/api/index.html or you can download this documentation to your own computer from java.sun.com/javase/6/download.jsp. For additional technical details on many aspects of Java development, visit java.sun.com/reference/docs/index.html.

1.8 Test-Driving a Java Application

In this section, you’ll run and interact with your first Java application. You’ll begin by running an ATM application that simulates the transactions that take place when using an ATM machine (e.g., withdrawing money, making deposits and checking account balances). You’ll learn how to build this application in the optional, object-oriented case study included in Chapters 18 and 10. For the purpose of this section, we assume you’re running Microsoft Windows.

In the following steps, you’ll run the application and perform various transactions. The elements and functionality you see in this application are typical of what you’ll learn to program in this book. [Note: We use fonts to distinguish between features you see on a screen (e.g., the Command Prompt) and elements that are not directly related to a screen. Our convention is to emphasize screen features like titles and menus (e.g., the File menu) in a semibold sans-serif Helvetica font and to emphasize non-screen elements, such as file names or input (e.g., ProgramName.java) in a sans-serif Lucida font. As you’ve already noticed, the defining occurrence of each key term is set in bold italic. In the figures in this section, we highlight the user input required by each step and point out significant parts of the application with lines and text. To make these features more visible, we have modified the background color of the Command Prompt windows.]

1. Checking your setup. Read the Before You Begin section of the book to confirm that you have set up Java properly on your computer and that you have copied the book’s examples to your hard drive.

2. Locating the completed application. Open a Command Prompt window. This can be done by selecting Start > All Programs > Accessories > Command Prompt. Change to the ATM application directory by typing cd C:examplesch01ATM, then press Enter (Fig. 1.2). The command cd is used to change directories.

Fig. 1.2. Opening a Windows XP Command Prompt and changing directories.

Image

3. Running the ATM application. Type the command java ATMCaseStudy (Fig. 1.3) and press Enter. Recall that the java command, followed by the name of the application’s .class file (in this case, ATMCaseStudy), executes the application. Specifying the .class extension when using the java command results in an error. [Note: Java commands are case sensitive. It is important to type the name of this application with a capital A, T and M in “ATM,” a capital C in “Case” and a capital S in “Study.” Otherwise, the application will not execute.] If you receive the error message, “Exception in thread "main" java.lang.NoClassDefFoundError: ATMCaseStudy,” your system has a CLASSPATH problem. Please refer to the Before You Begin section of the book for instructions to help you fix this problem.

Fig. 1.3. Using the java command to execute the ATM application.

Image

4. Entering an account number. When the application first executes, it displays a "Welcome!" greeting and prompts you for an account number. Type 12345 at the "Please enter your account number:" prompt (Fig. 1.4) and press Enter.

Fig. 1.4. Prompting the user for an account number.

Image

5. Entering a PIN. Once a valid account number is entered, the application displays the prompt "Enter your PIN:". Type "54321" as your valid PIN (Personal Identification Number) and press Enter. The ATM main menu containing a list of options will be displayed (Fig. 1.5).

Fig. 1.5. Entering a valid PIN number and displaying the ATM application’s main menu.

Image

6. Viewing the account balance. Select option 1, "View my balance", from the ATM menu (Fig. 1.6). The application then displays two numbers—the Available balance ($1000.00) and the Total balance ($1,200.00). The available balance is the maximum amount of money in your account which is available for withdrawal at a given time. In some cases, certain funds, such as recent deposits, are not immediately available for the user to withdraw, so the available balance may be less than the total balance, as it is here. After the account balance information is shown, the application’s main menu is displayed again.

Fig. 1.6. ATM application displaying user account balance information.

Image

7. Withdrawing money from the account. Select option 2, "Withdraw cash", from the application menu. You are then presented (Fig. 1.7) with a list of dollar amounts (e.g., 20, 40, 60, 100 and 200). You are also given the option to cancel the transaction and return to the main menu. Withdraw $100 by selecting option 4. The application displays "Please take your cash now." and returns to the main menu. [Note: Unfortunately, this application only simulates the behavior of a real ATM and thus does not actually dispense money.]

Fig. 1.7. Withdrawing money from the account and returning to the main menu.

Image

8. Confirming that the account information has been updated. From the main menu, select option 1 again to view your current account balance (Fig. 1.8). Note that both the available balance and the total balance have been updated to reflect your withdrawal transaction.

Fig. 1.8. Checking the new balance.

Image

9. Ending the transaction. To end your current ATM session, select option 4, "Exit" from the main menu (Fig. 1.9). The ATM will exit the system and display a goodbye message to the user. The application will then return to its original prompt asking for the next user’s account number.

Fig. 1.9. Ending an ATM transaction session.

Image

10. Exiting the ATM application and closing the Command Prompt window. Most applications provide an option to exit and return to the Command Prompt directory from which the application was run. A real ATM does not provide a user with the option to turn off the ATM machine. Rather, when a user has completed all desired transactions and chooses the menu option to exit, the ATM resets itself and displays a prompt for the next user’s account number. As Fig. 1.9 illustrates, the ATM application here behaves similarly. Choosing the menu option to exit ends only the current user’s ATM session, not the entire ATM application. To actually exit the ATM application, click the close (x) button in the upper-right corner of the Command Prompt window. Closing the window causes the running application to terminate.

1.9 Software Engineering Case Study: Introduction to Object Technology and the UML

Now we begin our early introduction to object orientation, a natural way of thinking about the world and writing computer programs. Chapters 18 and 10 all end with a brief Software Engineering Case Study section in which we present a carefully paced introduction to object orientation. Our goal here is to help you develop an object-oriented way of thinking and to introduce you to the Unified Modeling Language™ (UML™)—a graphical language that allows people who design software systems to use an industry standard notation to represent them.

In this only required section, we introduce object-oriented concepts and terminology. The optional sections in Chapters 28 and 10 present an object-oriented design and implementation of the software for a simple automated teller machine (ATM). The Software Engineering Case Study sections at the ends of Chapters 27

• analyze a typical requirements document that describes a software system (the ATM) to be built

• determine the objects required to implement that system

• determine the attributes the objects will have

• determine the behaviors these objects will exhibit

• specify how the objects interact with one another to meet the system requirements.

The Software Engineering Case Study sections at the ends of Chapters 8 and 10 modify and enhance the design presented in Chapters 27. Appendix H contains a complete, working Java implementation of the object-oriented ATM system.

You’ll experience a concise, yet solid introduction to object-oriented design with the UML. Also, you’ll sharpen your code-reading skills by touring the complete, carefully written and well-documented Java implementation of the ATM in Appendix H.

Basic Object Technology Concepts

We begin our introduction to object orientation with some key terminology. Everywhere you look in the real world you see objects—people, animals, plants, cars, planes, buildings, computers and so on. Humans think in terms of objects. Telephones, houses, traffic lights, microwave ovens and water coolers are just a few more objects. Computer programs, such as the Java programs you’ll read in this book and the ones you’ll write, are composed of lots of interacting software objects.

We sometimes divide objects into two categories: animate and inanimate. Animate objects are “alive” in some sense—they move around and do things. Inanimate objects, on the other hand, do not move on their own. Objects of both types, however, have some things in common. They all have attributes (e.g., size, shape, color and weight), and they all exhibit behaviors (e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleeps, crawls, walks and blinks; a car accelerates, brakes and turns; a towel absorbs water). We’ll study the kinds of attributes and behaviors that software objects have.

Humans learn about existing objects by studying their attributes and observing their behaviors. Different objects can have similar attributes and can exhibit similar behaviors. Comparisons can be made, for example, between babies and adults and between humans and chimpanzees.

Object-oriented design (OOD) models software in terms similar to those that people use to describe real-world objects. It takes advantage of class relationships, where objects of a certain class, such as a class of vehicles, have the same characteristics—cars, trucks, little red wagons and roller skates have much in common. OOD also takes advantage of inheritance relationships, where new classes of objects are derived by absorbing characteristics of existing classes and adding unique characteristics of their own. An object of class “convertible” certainly has the characteristics of the more general class “automobile,” but more specifically, the roof goes up and down.

Object-oriented design provides a natural and intuitive way to view the software design process—namely, modeling objects by their attributes and behaviors just as we describe real-world objects. OOD also models communication between objects. Just as people send messages to one another (e.g., a sergeant commands a soldier to stand at attention), objects also communicate via messages. A bank account object may receive a message to decrease its balance by a certain amount because the customer has withdrawn that amount of money.

OOD encapsulates (i.e., wraps) attributes and operations (behaviors) into objects—an object’s attributes and operations are intimately tied together. Objects have the property of information hiding. This means that objects may know how to communicate with one another across well-defined interfaces, but normally they are not allowed to know how other objects are implemented—implementation details are hidden within the objects themselves. We can drive a car effectively, for instance, without knowing the details of how engines, transmissions, brakes and exhaust systems work internally—as long as we know how to use the accelerator pedal, the brake pedal, the wheel and so on. Information hiding, as we’ll see, is crucial to good software engineering.

Languages like Java are object oriented. Programming in such a language is called object-oriented programming (OOP), and it allows computer programmers to implement an object-oriented design as a working system. Languages like C, on the other hand, are procedural, so programming tends to be action oriented. In C, the unit of programming is the function. Groups of actions that perform some common task are formed into functions, and functions are grouped to form programs. In Java, the unit of programming is the class from which objects are eventually instantiated (created). Java classes contain methods (which implement operations and are similar to functions in C) as well as fields (which implement attributes).

Java programmers concentrate on creating classes. Each class contains fields, and the set of methods that manipulate the fields and provide services to clients (i.e., other classes that use the class). The programmer uses existing classes as the building blocks for constructing new classes.

Classes are to objects as blueprints are to houses. Just as we can build many houses from one blueprint, we can instantiate (create) many objects from one class. You cannot cook meals in the kitchen of a blueprint; you can cook meals in the kitchen of a house.

Classes can have relationships with other classes. For example, in an object-oriented design of a bank, the “bank teller” class needs to relate to the “customer” class, the “cash drawer” class, the “safe” class, and so on. These relationships are called associations.

Packaging software as classes makes it possible for future software systems to reuse the classes. Groups of related classes are often packaged as reusable components. Just as realtors often say that the three most important factors affecting the price of real estate are “location, location and location,” people in the software community often say that the three most important factors affecting the future of software development are “reuse, reuse and reuse.” Reuse of existing classes when building new classes and programs saves time and effort. Reuse also helps programmers build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning.

Indeed, with object technology, you can build much of the software you’ll need by combining classes, just as automobile manufacturers combine interchangeable parts. Each new class you create will have the potential to become a valuable software asset that you and other programmers can use to speed and enhance the quality of future software development efforts.

Introduction to Object-Oriented Analysis and Design (OOAD)

To create the best software, you should follow a detailed process for analyzing your project’s requirements (i.e., determining what the system is supposed to do) and developing a design that satisfies them (i.e., deciding how the system should do it). Ideally, you would go through this process and carefully review the design (or have your design reviewed by other software professionals) before writing any code. If this process involves analyzing and designing your system from an object-oriented point of view, it is called an object-oriented analysis and design (OOAD) process.

Ideally, a group should agree on a strictly defined process for solving its problem and a uniform way of communicating the results of that process to one another. Although many different OOAD processes exist, a single graphical language for communicating the results of any OOAD process has come into wide use. This language, known as the Unified Modeling Language (UML), was developed in the mid-1990s under the initial direction of three software methodologists—Grady Booch, James Rumbaugh and Ivar Jacobson.

History of the UML

In the 1980s, increasing numbers of organizations began using OOP to build their applications, and a need developed for a standard OOAD process. Many methodologists—including Booch, Rumbaugh and Jacobson—individually produced and promoted separate processes to satisfy this need. Each process had its own notation, or “language” (in the form of graphical diagrams), to convey the results of analysis and design.

By the early 1990s, different organizations, and even divisions within the same organization, were using their own unique processes and notations. At the same time, these organizations also wanted to use software tools that would support their particular processes. Software vendors found it difficult to provide tools for so many processes. A standard notation and standard processes were needed.

In 1994, James Rumbaugh joined Grady Booch at Rational Software Corporation (now a division of IBM), and the two began working to unify their popular processes. They soon were joined by Ivar Jacobson. In 1996, the group released early versions of the UML to the software engineering community and requested feedback. Around the same time, an organization known as the Object Management Group™ (OMG™) invited submissions for a common modeling language. The OMG (www.omg.org) is a nonprofit organization that promotes the standardization of object-oriented technologies by issuing guidelines and specifications, such as the UML. Several corporations—among them HP, IBM, Microsoft, Oracle and Rational Software—had already recognized the need for a common modeling language. In response to the OMG’s request for proposals, these companies formed UML Partners—the consortium that developed the UML version 1.1 and submitted it to the OMG. The OMG accepted the proposal and, in 1997, assumed responsibility for the continuing maintenance and revision of the UML. The UML version 2 now available marks the first major revision of the UML since the 1997 version 1.1 standard. We present UML 2 terminology and notation throughout this book.

What Is the UML?

The UML is now the most widely used graphical representation scheme for modeling object-oriented systems. It has indeed unified the various popular notational schemes. Those who design systems use the language (in the form of diagrams) to model their systems.

An attractive feature of the UML is its flexibility. The UML is extensible (i.e., capable of being enhanced with new features) and is independent of any particular OOAD process. UML modelers are free to use various processes in designing systems, but all developers can now express their designs with one standard set of graphical notations.

The UML is a complex, feature-rich graphical language. In our Software Engineering Case Study sections, we present a concise subset of these features. We then use this subset to guide you through an end-to-end design experience with the UML.

Web UML Resources

For more information about the UML, refer to the following websites:

www.uml.org

This UML resource page from the Object Management Group (OMG) provides specification documents for the UML and other object-oriented technologies.

www.ibm.com/software/rational/uml

This is the UML resource page for IBM Rational—the successor to the Rational Software Corporation (the company that created the UML).

en.wikipedia.org/wiki/Unified_Modeling_Language

Wikipedia’s definition of the UML. This site also provides links to many additional UML resources.

Recommended Readings

The following books provide information about object-oriented design with the UML:

Ambler, S. The Object Primer: Agile Model-Driven Development with UML 2.0, Third Edition. New York: Cambridge University Press, 2005.

Arlow, J., and I. Neustadt. UML and the Unified Process: Practical Object-Oriented Analysis and Design, Second Edition. Boston: Addison-Wesley Professional, 2006.

Fowler, M. UML Distilled, Third Edition: A Brief Guide to the Standard Object Modeling Language. Boston: Addison-Wesley Professional, 2004.

Rumbaugh, J., I. Jacobson and G. Booch. The Unified Modeling Language User Guide, Second Edition. Boston: Addison-Wesley Professional, 2006.

Section 1.9 Self-Review Exercises

1.1 List three examples of real-world objects that we did not mention. For each object, list several attributes and behaviors.

1.2 Pseudocode is _________.

a) another term for OOAD

b) a programming language used to display UML diagrams

c) an informal means of expressing program logic

d) a graphical representation scheme for modeling object-oriented systems

1.3 The UML is used primarily to _________.

a) test object-oriented systems

b) design object-oriented systems

c) implement object-oriented systems

d) Both a and b

Answers to Section 1.9 Self-Review Exercises

1.1 [Note: Answers may vary.] a) A television’s attributes include the size of the screen, the number of colors it can display, its current channel and its current volume. A television turns on and off, changes channels, displays video and plays sounds. b) A coffee maker’s attributes include the maximum volume of water it can hold, the time required to brew a pot of coffee and the temperature of the heating plate under the coffee pot. A coffee maker turns on and off, brews coffee and heats coffee. c) A turtle’s attributes include its age, the size of its shell and its weight. A turtle walks, retreats into its shell, emerges from its shell and eats vegetation.

1.2 c.

1.3 b.

1.10 Web 2.0

The web literally exploded in the mid-to-late 1990s, but hard times hit in the early 2000s due to the dot com economic bust. The resurgence that began in 2004 or so has been named Web 2.0. The first Web 2.0 Conference was held in 2004. A year into its life, the term “Web 2.0” garnered about 10 million hits on the Google search engine, growing to 60 million a year later. Google is widely regarded as the signature company of Web 2.0. Some others are Craigslist (free classified listings), Flickr (photo sharing), del.icio.us (social bookmarking), YouTube (video sharing), MySpace and FaceBook (social networking), Salesforce (business software offered as an online service), Second Life (a virtual world), Skype (Internet telephony) and Wikipedia (a free online encyclopedia).

At Deitel & Associates, we launched our Web 2.0-based Internet Business Initiative in 2005. We’re researching the key technologies of Web 2.0 and using them to build Internet businesses. We’re sharing our research in the form of Resource Centers at www.deitel.com/resourcecenters.html. Each week, we announce the latest Resource Centers in our newsletter, the Deitel® Buzz Online (www.deitel.com/newsletter/subscribe.html). Each lists many links to (mostly) free content and software on the Internet.

We include a substantial treatment of web services (Chapter 23). Web services are frequently used in the application development methodology of mashups in which you can rapidly develop powerful and intriguing applications by combining organizations’ complementary web services and other forms of information feeds. A popular mashup is www.housingmaps.com which combines real estate listings of www.craigslist.org with the mapping capabilities of Google Maps to offer maps that show the locations of apartments for rent in a given area.

Ajax is one of the premier technologies of Web 2.0. Though the term’s use exploded in 2005, it’s just a term that names a group of technologies and programming techniques that have been in use since the late 1990s. Ajax helps Internet-based applications perform like desktop applications—a difficult task, given that such applications suffer transmission delays as data is shuttled back and forth between your computer and other computers on the Internet. Using Ajax techniques, applications like Google Maps have achieved excellent performance and the look and feel of desktop applications. Although we don’t discuss “raw” Ajax programming (which is quite complex) in this text, we do show in Chapter 22 how to build Ajax-enabled applications using JavaServer Faces (JSF) Ajax-enabled components.

Blogs are websites (currently more than 100 million of them) that are like online diaries, with the most recent entries appearing first. Bloggers quickly post their opinions about news, product releases, politics, controversial issues, and just about everything else. The collection of all blogs and the blogging community is called the blogosphere and is becoming increasingly influential. Technorati is a leading blog search engine.

RSS feeds enable sites to push information to subscribers. A common use of RSS feeds is to deliver the latest blog postings to people who subscribe to blogs. The RSS information flows on the Internet are growing exponentially.

Web 3.0 is another name for the next generation of the web also called the Semantic Web. Web 1.0 was almost purely HTML-based. Web 2.0 is making increasing use of XML, especially in technologies like RSS feeds. Web 3.0 will make deep use of XML, creating a “web of meaning.” If you’re an entrepreneur looking for business opportunities, check out our Web 3.0 Resource Center.

To follow the latest developments in Web 2.0, read www.techcrunch.com and www.slashdot.org and check out the growing list of Web 2.0-related Resource Centers at www.deitel.com/resourcecenters.html.

1.11 Software Technologies

In this section, we discuss a number of software engineering buzzwords that you’ll hear in the software development community. We’ve created Resource Centers on most of these topics, with more on the way.

Agile Software Development is a set of methodologies that try to get software implemented quickly with fewer resources then previous methodologies. Check out the Agile Alliance (www.agilealliance.org) and the Agile Manifesto (www.agilemanifesto.org).

Extreme programming (XP) is one of many agile development methodologies. It tries to develop software quickly. The software is released frequently in small increments to encourage rapid user feedback. XP recognizes that the users’ requirements change often and that software must meet those new requirements quickly. Programmers work in pairs at one machine so code review is done immediately as the code is created.

Refactoring involves reworking code to make it clearer and easier to maintain while preserving its functionality. It’s widely employed with agile development methodologies. Many refactoring tools are available to do major portions of the reworking automatically.

Design patterns are proven architectures for constructing flexible and maintainable object-oriented software. The field of design patterns tries to enumerate those recurring patterns, and encourage software designers to reuse them to develop better quality software with less time, money and effort.

Game programming. The computer game business is larger than the first-run movie business. Check out our Game Programming and Programming Projects Resource Centers.

Open source software is a style of developing software in contrast to proprietary development that dominated software’s early years. With open source development, individuals and companies contribute their efforts in developing, maintaining and evolving software in exchange for the right to use that software for their own purposes, typically at no charge. Open source code generally gets scrutinized by a much larger audience than proprietary software, so bugs are often removed faster. Open source also encourages more innovation. Sun recently open sourced Java. Some organizations you’ll hear a lot about in the open source community are the Eclipse Foundation (the Eclipse IDE is popular for Java software development), the Mozilla Foundation (creators of the Firefox browser), the Apache Software Foundation (creators of the Apache web server) and SourceForge (which provides the tools for managing open source projects and currently has over 150,000 open source projects under development).

Linux is an open source operating system and one of the greatest successes of the open source movement. MySQL is an open source database management system. PHP is a popular open source server-side Internet “scripting” language for developing Internet-based applications. LAMP is an acronym for the set of open source technologies that many developers used to build web applications—it stands for Linux, Apache, MySQL and PHP (or Perl or Python—two other languages used for similar purposes).

Ruby on Rails combines the scripting language Ruby with the Rails web application framework developed by the company 37Signals. Their book, Getting Real, is a must read for today’s web application developers; read it free at gettingreal.37signals.com/toc.php. Many Ruby on Rails developers have reported significant productivity gains over using other languages when developing database-intensive web applications.

With Software as a Service (SAAS) the software, instead of being installed locally, runs on servers elsewhere on the Internet. When that server is updated, all clients worldwide see the new capabilities; no local installation is needed. You access the service through a browser—these are quite portable so you can run the same applications on different kinds of computers from anywhere is the world. Salesforce.com, Google, and Microsoft’s Office Live and Windows Live all offer SAAS.

1.12 Wrap-Up

This chapter introduced basic object technology concepts, including classes, objects, attributes, behaviors, encapsulation, inheritance and polymorphism. You learned the steps for creating and executing a Java application using Sun’s JDK 6. The chapter explored the history of the Internet and the World Wide Web, and Java’s role in developing distributed client/server applications for the Internet and the web. You also learned about the history and purpose of the UML—the industry-standard graphical language for modeling software systems. Finally, you “test-drove” a sample Java application. In Chapter 2, you’ll create your first Java applications.

1.13 Web Resources

This section provides many resources that will be useful to you as you learn Java. The sites include Java resources, Java development tools and our own websites where you can find downloads and resources associated with this book. We also provide a link where you can subscribe to our free Deitel® Buzz Online e-mail newsletter.

Deitel & Associates Websites

www.deitel.com

Contains updates, corrections and additional resources for all Deitel publications.

www.deitel.com/newsletter/subscribe.html

Subscribe to the free Deitel® Buzz Online e-mail newsletter to follow the Deitel & Associates publishing program, including updates and errata to this book.

www.deitel.com/books/javafp/

The Deitel & Associates home page for Java for Programmers. Here you’ll find links to the book’s examples (also included on the CD that accompanies the book) and other resources.

Deitel Java Resource Centers

www.deitel.com/Java/

Our Java Resource Center focuses on the enormous amount of Java free content available online. Start your search here for resources, downloads, tutorials, documentation, books, e-books, journals, articles, blogs and more that will help you develop Java applications.

www.deitel.com/JavaSE6Mustang/

Our Java SE 6 Resource Center is your guide to the latest release of Java. The site includes the best resources we found online to help you get started with Java SE 6 development.

www.deitel.com/JavaEE5/

Our Java Enterprise Edition 5 (Java EE 5) Resource Center.

www.deitel.com/JavaCertification/

Our Java Certification and Assessment Testing Resource Center.

www.deitel.com/JavaDesignPatterns/

Our Java Design Patterns Resource Center. In their book, Design Patterns: Elements of Reusable Object-Oriented Software (Boston: Addison-Wesley Professional, 1995), the “Gang of Four” (E. Gamma, R. Helm, R. Johnson, and J. Vlissides) describe 23 design patterns that provide proven architectures for building object-oriented software systems. In this resource center, you’ll find discussions of many of these and other design patterns.

www.deitel.com/CodeSearchEngines/

Our Code Search Engines and Code Sites Resource Center includes resources developers use to find source code online.

Sun Microsystems Websites

java.sun.com/new2java/

The “New to Java Center” on the Sun Microsystems website features online training resources to help you get started with Java programming.

java.sun.com/javase/downloads/index.jsp

The download page for the Java Development Kit 6 (JDK 6) and its documentation. The JDK includes everything you need to compile and execute your Java SE 6 (Mustang) applications.

java.sun.com/javase/6/webnotes/install/index.html

Instructions for installing JDK 6 on Solaris, Windows and Linux platforms.

java.sun.com/javase/6/docs/api/index.html

The online site for the Java SE 6 API documentation.

java.sun.com/javase

The home page for the Java Standard Edition platform.

java.sun.com

Sun’s Java technology home page provides downloads, references, forums, online tutorials and more.

developers.sun.com

Sun’s home page for Java developers provides downloads, APIs, code samples, articles with technical advice and other resources on the best Java development practices.

Editors and Integrated Development Environments

www.eclipse.org

The Eclipse development environment can be used to develop code in any programming language. You can download the environment and several Java plug-ins to develop your Java programs.

www.netbeans.org

The NetBeans IDE. One of the most widely used, freely distributed Java development tools.

www.codegear.com/products/jbuilder

Codegear provides a free Turbo Edition version of its popular Java IDE JBuilder. The site also provides trial versions of the Enterprise and Professional editions.

www.blueJ.org

BlueJ—a free tool designed to help teach object-oriented Java to new programmers.

www.jgrasp.org

jGRASP downloads, documentation and tutorials. This tool displays visual representations of Java programs to aid comprehension.

www.jedit.org

jEdit—a text editor written in Java.

developers.sun.com/prodtech/javatools/jsenterprise/index.jsp

Sun Java Studio Enterprise IDE—the Sun Microsystems enhanced version of NetBeans.

www.jcreator.com

JCreator—a popular Java IDE. JCreator Lite Edition is available as a free download. A 30-day trial version of JCreator Pro Edition is also available.

www.textpad.com

TextPad—compile, edit and run your Java programs from this editor that provides syntax coloring and an easy-to-use interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset