• Không có kết quả nào được tìm thấy

Java, Java, Java

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Chia sẻ "Java, Java, Java"

Copied!
856
0
0

Loading.... (view fulltext now)

Văn bản

Much of the discussion of inheritance and polymorphism that was previously woven throughout the first five chapters of the second edition has been integrated into a new Chapter 8. Thus, instead of using constructed examples of OO concepts, instructors can use some of Java's fundamental features—the class library, Swing, and GUI components—to motivate these discussions in a natural way.

Table 1: Table of Contents for the Third Edition.
Table 1: Table of Contents for the Third Edition.

OBJECTIVES

OUTLINE

Computers, Objects, and Java

Welcome

Welcome to Java, Java, Java, a book that introduces you to object-oriented programming using the Java language. We introduce the Java programming language and conclude the chapter by exploring the principles of object-oriented programming and how Java is an object-oriented programming language.

What Is a Computer?

In a sense, main memory acts as the computer's scratch pad, temporarily storing both programs and data while a program is running. All of these devices are non-volatile, meaning they retain information when the computer is turned off.

Special Topic: Processors Then and Now

  • Networks, the Internet and the World Wide Web
  • Why Study Programming?
  • Programming Languages
  • Why Java?
  • What Is Object-Oriented Programming?
    • Basic Object-Oriented Programming Metaphor

One of the best reasons to study programming is that it is a creative and enjoyable problem-solving activity. This is one of the reasons why Java is so well suited to supporting applications on enterprise networks.

Figure 2: WWW: The client’s browser requests a page from a Web server. When the HTML  doc-ument is returned, it is interpreted and displayed by the browser.
Figure 2: WWW: The client’s browser requests a page from a Web server. When the HTML doc-ument is returned, it is interpreted and displayed by the browser.

Interacting Objects

  • What is an Object?
  • Attributes and Values
  • Actions and Messages
  • What is a Class?
  • Variables and Methods
  • Instance versus Class Variables and Methods
  • Class Hierarchy and Inheritance
  • Principles of Object-Oriented Design

As you can see, the attributes of an object are listed in a second partition of the UML diagram. An instance variable (or instance method) is a variable (or method) that belongs to an object.

Figure 5: In UML, objects are rep- rep-resented by rectangles that are  la-beled with a two-part label of the form id:Type
Figure 5: In UML, objects are rep- rep-resented by rectangles that are la-beled with a two-part label of the form id:Type

EXERCISES

Extensibility: Objects should be designed so that their functionality can be extended to perform more specialized tasks. In other words, pick one of your car's systems, such as the brake system, and analyze it in terms of divide-and-conquer, encapsulation, information hiding, and interface.

Java Program Design and Development

Introduction

This chapter introduces some of the basic concepts and techniques involved in designing and developing Java programs. By the end of the chapter, you will be able to design and write a Java application that "sings" your favorite song.

Designing Good Programs

  • The Software Engineering Life Cycle

As an example of a riddle, consider the question "What is black and white and what do you read in it?" The answer, of course, is a newspaper. In this way the program is divided into an interactive collection- Divide and conquer objects.

Figure 1.1: An overview of the program development process.
Figure 1.1: An overview of the program development process.

Designing a Riddle Program

  • Problem Decomposition
  • Object Design
  • Data, Methods, and Algorithms
  • Coding into Java
  • Syntax and Semantics
  • Testing, Debugging, and Revising
  • Writing Readable Programs

Thus, for this simple problem, we only need to design one new type of object - a riddle - whose primary role will be to represent the question and answer of a riddle. We will use the Riddle() constructor to give specific values ​​to Riddle's question and answer variables.

Figure 1.4: The Riddle class definition.
Figure 1.4: The Riddle class definition.

Special Topic: Grace Hopper and the First Computer Bug

Java Language Elements

  • Comments
  • Program Layout
  • Keywords and Identifiers
  • Data Types and Variables
  • Statements
  • Expressions and Operators

In the first case, the value on the right side is the string literal "Hello, World!", which is saved as the greeting. In the third case, the value on the right side is 25, which is determined by adding 10 and 15 together.

Table 1.1: Java keywords.
Table 1.1: Java keywords.

SELF-STUDY EXERCISES

  • Class Definition
  • Declaring an Instance Variable
  • Defining an Instance Method
  • Java Application Programs
  • Creating and Using Objects
  • Java JFrames
  • Java Library Packages
  • The import Statement
  • Qualified Names in Java
  • Editing, Compiling, and Running a Java Pro- gram
    • Java Development Environments
    • Editing a Program
    • Compiling a Program
    • Running a Java Application Program
    • Running a Java Swing Program
  • From the Java Library: System and PrintStream

As in the case of the HelloWorld console application program, HelloWorldCanvas consists of a class definition. When referenced as part of a package, the class name is the last part of the name.

Figure 1.9: HelloWorldCanvas program.
Figure 1.9: HelloWorldCanvas program.

SOLUTIONS TO

Calculate the sum of two numbers asN − M. EXERCISE 1.4 Suppose you have a Java program stored in a file named Test.java. Describe an algorithm that uses the queues and the matches to calculate when exactly 45 minutes have passed. It must store the current temperature in an instance variable of type double, and it must have two public methods, setTemp(double t), which assigns to the instance variable, engetTemp(), which returns the value of the instance variable.

UML EXERCISES

This class must have one public method, calcTax(double purchase), which returns a double whose value is purchase times the tax rate.

Objects: Using, Creating, and Defining

Introduction

Then we examine how user-defined classes are used by doing a detailed walkthrough of the Riddleclass we saw in Chapter 1. We then present a detailed example of the programming development process by designing a class that models a certain two-person game and implementing the class.

Using String Objects

  • Creating and Combining Strings

Once you have constructed a Stringobject, you can use any of the methods shown on it in Figure 2.1. As we have already seen, we use dot notation to call one of the methods. So we first mention the name of the object followed by a dot (period), followed by the name of the method.

Figure 2.4 shows a program that uses string concatenation to create
Figure 2.4 shows a program that uses string concatenation to create

Drawing Shapes with a Graphics Object (Optional)(Optional)

  • Graphics Drawing Methods

Instead, we'll focus on the information needed to make good use of the g.drawString() method. We could specify one rectangle with a top left corner 25 pixels to the right of the left edge of the JFrame and 25 pixels down from the top edge. A location 25 pixels to the right of the left edge of the rectangle and 25 pixels down from the top edge of the rectangle has coordinates x = 50andy = 50.

Figure 2.7: “Hello, World!” is drawn at coordinate (10, 10) and
Figure 2.7: “Hello, World!” is drawn at coordinate (10, 10) and

Class Definition

  • The Riddle Class
  • The RiddleUser Class
  • Object Instantiation: Creating Riddle Instances
  • Interacting with Riddle s
  • Define, Create, Use

A user interface is an object or class that handles the interaction between a program's user and the rest of the program's computational tasks. Note that we use the general term computational object to distinguish the rest of the program's computations from the user interface. Of course, the exact nature of the calculation will vary from program to program, as will the details of the user interface.

Figure 2.9: The HelloWorldGraphic class is a Java Swing program that shows how to use color and drawing methods.
Figure 2.9: The HelloWorldGraphic class is a Java Swing program that shows how to use color and drawing methods.

CASE STUDY: Simulating a Two-Person Game

  • Designing a OneRowNim class
  • Defining the OneRowNim Class
  • Testing the OneRowNim Class
  • Flow of Control: Method Call and Return
  • Tracing the OneRowNim Program
  • Object-Oriented Design: Basic Principles

Similarly, we followed the convention of marking object instance variables—OneRowNim instance variables—that remain hidden from other objects, so we marked them as private (−). A protected class-level variable can only be accessed by subclasses of the class in which it is declared or by other classes belonging to the same package. Three methods are described as changing the values ​​of nSticksand player instance variables, and the fourth, report(), writes information to the console.

Figure 2.16 is a UML class diagram that summarizes this design of the
Figure 2.16 is a UML class diagram that summarizes this design of the

Special Topic: Alan Kay and the Smalltalk Language

Keyboard Input with the Scanner Class

Keyboard input will allow us to create examples of command-line interfaces for interactive programs. We should mention that since the scan class is designed as a flexible tool for recognizing chunks of data from any input stream, it has some properties that may be unexpected and not entirely compatible with simple keyboard input. Real-world software applications that use keyboard input must carefully handle the possibility that a user will enter something unexpected.

Figure 2.26: A very brief program with a Scanner object used for keyboard input
Figure 2.26: A very brief program with a Scanner object used for keyboard input

Keyboard Input with the KeyboardReader Class

Methods that are used only for internal operations of the class must be declared private. Then define methods that perform the following operations on its number: get, double, triple, square, and cube. Set the initial value of the number with a constructor as was done with instance variables in theRiddleclass.

Introduction

Passing Information to an Object

  • Arguments and Parameters
  • Passing an int value to a OneRowNim method
  • Passing keyboard input to takeSticks()

A parameter's scope is limited to the body of the method in which it is declared. In particular, the scope of a parameter is the entire body of the method in which it is declared. We will use the term parameter to refer to the formal parameter—the variable used to pass data to a method—that occurs in the method definition.

Figure 3.1: The OneRowNim class definition with takeSticks() method.
Figure 3.1: The OneRowNim class definition with takeSticks() method.

Constructor Methods

  • Default Constructors
  • Constructor Overloading and Method Signatures
  • Constructor Invocation

Both have the same name, but the first takes no parameters, while the second takes a single int parameter. A method signature consists of the method's name, plus the number, types, and order of its formal parameters. The signature of the method call—its name and its number, types, and sequence.

Retrieving Information from an Object

  • Invoking a Method That Returns a Value
  • An Expanded OneRowNim Class

Before we discuss how the value returned by the method is used in the method call, let's review one more method definition. Many methods that return a value perform a calculation instead of simply returning the value of the instance variable. In each statement, we can replace the method call with the value it returns.

Figure 3.5: A UML class diagram for the expanded OneRowNim.
Figure 3.5: A UML class diagram for the expanded OneRowNim.

Passing a Value and Passing a Reference

The reason is that during the execution of the method both gameandgre refer to the exact same object (see Figure 3.10). This illustrates that when passing a reference variable to a method, it is possible for the method to change the state of the object it is associated with. When a reference to an object is passed to a method, any changes made to the object within the method will persist at the end of the method's execution.

Figure 3.8: Tracing the state of variables k and n in PrimitiveCall (a) Just  be-fore calling myMethod(k) in main
Figure 3.8: Tracing the state of variables k and n in PrimitiveCall (a) Just be-fore calling myMethod(k) in main

Flow of Control: Control Structures

  • The Simple If Statement
  • The if-else Statement
  • The Nested if/else Multiway Selection Structure
  • The While Structure

Merely indenting the statements that follow the if statement does not change the logic of the if statement. This segment will always print "Two" because secondprintln() is not part of an if statement. As in the case of a simple if statement, the keyword if followed by the If-else syntax is a logical expression in parentheses followed by the statement1 which.

Figure 3.11: Flowchart of the if statement. Diamond-shaped  sym-bols at the branch points contain boolean expressions
Figure 3.11: Flowchart of the if statement. Diamond-shaped sym-bols at the branch points contain boolean expressions

SELF-STUDY EXERCISE

Testing an Improved OneRowNim

Also note that the if/elsemultiway structure is used to handle the three cases where the parameter number is less than one, greater than three, or a valid number. Let's define a method called getWinner() that returns the number of the winning player if the game is over. We now have the final version (for this chapter) of the OneRowNim class, the implementation of which is given in Figure 3.16.

Figure 3.16: The OneRowNim class with improved methods.
Figure 3.16: The OneRowNim class with improved methods.

Special Topic: Intelligent Agents

Object-Oriented Design: Inheritance and Polymorphism

Java's inheritance mechanism and how it promotes the generality and extensibility of the object-oriented approach. The higher up in the class hierarchy a method is defined, the more widespread its use can be. For example, suppose we design a class, Student, as a subclass of Object and define its toString() method to return the student ID number.

Drawing Lines and Defining Graphical Methods (Optional)

As we've seen in this example, defining methods with parameters to draw an object allows for code reuse and allows you to draw a complex scene by calling a collection of simpler methods.

CHAPTER SUMMARYTechnical Terms

Then write methodsday1(),day2(), and so on, each of which prints its version of the verse. The name can be any string, but the rating must be one of the following values: "high". Write another method with the signaturehadAnX(String s), which sings the "had a duck" part of the verse, and a method with A(String sound) to sing the "with a quack quack here" part of the verse.

Figure 3.21: Flowchart of the if- if-else version of the getStatus() method.
Figure 3.21: Flowchart of the if- if-else version of the getStatus() method.

ADDITIONAL EXERCISES

Input/Output: Designing the User Interface

Introduction

An input operation is any action that transfers data from the user to the computer's main memory via one of the computer's input devices. An output operation is any operation that transfers data from the computer's main memory to one of the computer's output devices. These interfaces can be used interchangeably with the material in most of the subsequent chapters.

The User Interface

One of the most important parts of learning a programming language is learning how to program an application to accept input and create output (I/O). Indeed, one of the most important design principles we emphasize in this chapter is that the user interface should be designed to function independently of the computing task. JAVA EFFECTIVE DESIGN The User Interface Module Separating the user interface from the computer object is a good way to divide the work in programs that perform I/O.

A Command-Line Interface

  • Using a BufferedReader to Input Strings from the Keyboard
  • Inputting Numbers from the Keyboard
  • Designing a Keyboard Reader Class
  • Designing a Command-Line Interface

This is the method we'll call when we just want to get the string the user typed from the keyboard. This gives GreeterAppa a way to directly reference the UI whenever it needs keyboard input. Note that for this problem, the user will have to enter integers on the keyboard.

Figure 4.3: The Java console win- win-dow.
Figure 4.3: The Java console win- win-dow.

A Graphical User Interface (GUI)

  • Java’s GUI Components
  • Class Inheritance: Extending a Superclass
  • Top-level Windows
  • GUI Components for Input, Output, and Control
  • Adding GUI Components to a Top-Level Window
  • Controlling the GUI’s Action
  • The ActionListener Interface
  • Connecting the GUI to the Computational Object
  • Using the GUI in a Java Application

The constructor method illustrates how to use some of the methods inherited from JFrame. In this way, all components involved in receiving user data will be organized in one panel. This will help us bring together all the different concepts we have introduced.

Figure 4.10: Various GUI com- com-ponents from the javax.swing package. [Artwork: We need to label the components.]
Figure 4.10: Various GUI com- com-ponents from the javax.swing package. [Artwork: We need to label the components.]

Case Study: The One Row Nim Game

  • A Command-line Interface to OneRowNim
  • A GUI for OneRowNim

As long as the game is not over, the body of the loop will be executed. If left to the UI, it is possible that a programming error could lead to a loss of game integrity. Following the design we used in the GUI for our greeter application, we can use a JTextField for the user's input and a JTextArea for the game's output.

Figure 4.22: Definition of OneRowNimApp , a command-line interface to the OneRowNim .
Figure 4.22: Definition of OneRowNimApp , a command-line interface to the OneRowNim .

From the Java Library: java.io.File and File Input (Optional)

  • File Input with the File and Scanner Classes

Because we use Java's built-in event loop, the GUI will continue to respond to user events unless we prevent it from doing so. Here we apply what we've learned about Java's event programming model: we define one or more of our elements to serve as an action listener, and we design algorithms to handle action events that occur on that element. Others will be covered in Chapter 13, which provides a more comprehensive look at GUI capabilities in Java.

Hình ảnh

Figure 2: WWW: The client’s browser requests a page from a Web server. When the HTML  doc-ument is returned, it is interpreted and displayed by the browser.
Figure 13: The ChessPiece hier- hier-archy.
Figure 1.1: An overview of the program development process.
Figure 1.4: The Riddle class definition.
+7

Tài liệu tham khảo

Tài liệu liên quan

Preface III Section 1 1 Solid State Behavior Chapter 1 3 Issues in Solid-State Physics by Roberto Raúl Deza Chapter 2 19 Lagrangian Quantum Mechanics: A Fully Relativistic Theory