giáo trình Java By Example phần 6
Mô tả tài liệu
Tham khảo tài liệu 'giáo trình java by example phần 6', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả
Tóm tắt nội dung
they identify a program object). Using the rules given, the following are valid identifiers in a Java program: The following identifiers are not valid in a Java program: likely to change from one program run to another, the number of vehicles that the garage can hold would In this line, the keyword int represents the data type, which is integer. Java has eight different data types, all of which represent different kinds of values in a program. In this section, you'll learn what kinds of values these various data types The most common values used in computer programs are integers, which represent whole number values of the value that's allowed depends on the integer data type you choose. (Unsigned values, which Java does not support, can hold only positive numbers.) In Java, you declare a byte value like this: In the preceding line, byte is the data type for the value, and identifier is the variable's name. After Java executes the preceding line, your program will have a variable named count that currently Next in the integer data types is int, which can hold a value from -2,147,483,648 to 2,147,483,647. The int data type can hold such large numbers because it The final integer data type in the Java language is long, which takes up a whopping 64 bits (eight bytes) How do you know which integer data type to use in your program? Whereas integer values can hold only whole numbers, the floating-point data types can hold values with Java, a value declared as float can hold a number in the range from around -3.402823 x 10 38 to This value is the type of floating-point number Both of the preceding values are equivalent, and you can use either form in a Java program. The second type of floating-point data, double, represents a double-precision value, which is a much When using floating-point numbers in your programs, the same rule Often in your programs, you'll need a way to represent character values rather than just numbers. In order to provide storage for character values, Java features the char data type, which is 16 bits. However, the size of the char data type has little to do with the values it can hold. characters, which you don't need to worry about in this book.) You declare a char value like this: In the second example, you're not only declaring the variable c as a char, but also setting its value to an backspace character, you might write something like the following in your Java program: When you want to use these characters in your program's data, you must also precede example, you might need to know whether a part of your program executed properly. can use Boolean values, which are represented in Java by the boolean data type. Table 5.2 summarizes Java's various data types. might use each data type in an actual program. Table 5.2 Summary of Java's Data Types. Type Value When you write your Java programs, you can't just declare your variables willy-nilly all over the place. worry about that just yet.) Specifically, program blocks include things like classes, functions, and loops, As you'll see when you start writing full-length Java programming, all programs Suppose you've written the small Java program shown in Listing 5.3. don't know much about writing Java programs. program. public class Block1 extends Applet value1 = 45; value1 = 100; Now look at the variables being used in this program. The first variable defined in the program is The second variable in the program, value2, is defined inside the Block2 block, where it's both In the Block3 block, the program tries to assign a value to value2. If you tried to compile this program, you'd see that this line creates an error message, as shown usually declare variables that you need in many places, so that they are in scope in the entire class. hand, you'll have lots of variables that you use only inside one particular program block. your program uncluttered by being sure to declare these types of variables only in the blocks in which Java, like all programming languages, features many data types that you can use for constants and variables in your programs. Name the eight data types used in Java.4. Suppose you need to write a Java program that calculates an employee's paycheck for a given Using the variables you declared in exercise 1, write the program lines needed to perform the Using Figure 5.1 as a guide, create a new figure that adds a program block to the class such that any variables declared in the new block cannot be accessed in any other program block. Displaying Text in an Applet In the previous chapter, you learned how you can store various types of values in your Java programs. programs. Displaying Text in an Applet one of Java's graphical-text functions. method to display a single line of text. Listing 6.1 Applet1.java: An Applet That Displays a Single Line of Text. import java.applet.*; public class Applet1 extends Applet Tell Java that the program uses classes in the awt package. Tell Java that the program uses classes in the applet package. Derive the Applet1 class from Java's Applet class. Override the Applet class's paint() method. Figure 6.2 : When you run the Applet1 applet, you'll see a single line of text in <applet code="Applet1.class" name="Applet1"> </applet> Example: Creating and Running Applet1 you need to know how to create and run the many applets that you'll find in this book. All the applets that Type Listing 6.1 and save it in the CLASSES folder as an ASCII file. Applet1.java. Type javac Applet1.java to compile the Applet1 applet. Also, make sure you typed the command line javac Applet1.java properly. When the compiler finishes, you'll have the file Applet1.class in your CLASSES directory. Figure 6.3 : The Applet1.class file must compile with no errors. Type Listing 6.2 and save it as an ASCII file to your CLASSES folder. Java calls paint() whenever the applet's display area (or canvas, The paint() method always gets called when the applet first You run the applet, Java calls paint() when the applet appears, and paint() calls drawString(), which displays the text string drawString() is a method of the Graphics class. Graphics class to the paint() method and that object is called g. tells Java to call the g object's drawString() method. arguments, which are values that you need to send to the method. Figure 6.4 : Here, Applet1 displays the text at position 25,25. add a control of the TextField class in your applet. Figure 6.5 : The Applet2 applet displays an area in which you can type. Listing 6.3 Applet2.java: Getting Input from the User. import java.applet.*; public class Applet2 extends Applet Tell Java that the program uses classes in the awt package. Tell Java that the program uses classes in the applet package. Derive the Applet2 class from Java's Applet class. Declare textField as an object of the TextField class. Override the Applet class's init() method. Add the TextField object to the applet's display. To run the Applet2 applet yourself, you'll need to type and save the source code, naming it Applet2.java. Applet2.java at the MS-DOS prompt), which gives you the Applet2.class file. object of the TextField class, which represents a control very much like a standard Windows edit box. The program declares the control like this: In Applet2, when init() gets called, textField has already been declared as an object of the TextField class, but textField hasn't yet been assigned a value. The value in the The next step is to add the object to the applet's display area, like this: The add() method's single argument is the control you want to add to the applet. After creating the control and adding it to the applet, the control will automatically appear when Java In the Applet2 applet, you can type all you like in the TextField control, but how do you get the text Follow the steps below to create Applet3, a new Type Listing 6.4 and save it in the CLASSES folder as an ASCII file. Applet3.java. Listing 6.4 Applet3.java: Source Code for the Applet3 Applet. import java.applet.*; public class Applet3 extends Applet Tell Java that the program uses classes in the awt package. Tell Java that the program uses classes in the applet package. Derive the Applet3 class from Java's Applet class. Declare textField as an object of the TextField class. Override the Applet class's init() method. Add the TextField object to the applet's display. Override the Applet class's paint() method. Override the Applet class's action() method. Type javac Applet3.java to compile the Applet3 applet. sure you typed the command line javac Applet3.java properly. When you run Applet3, go ahead and type some text into the TextField control. Enter, the text appears in the applet's display area, right below the control (Figure 6.6). Figure 6.6 : Applet3 can display the text you type into the TextField control. If you look at the Applet3 program code, you can see that you've added a paint() method. This line declares a variable called s to be an object of the String class, and then it sets s equal to the (The String class is another of Java's built-in classes that you'll learn more For now, just know that this class represents text strings.) You can see in this line that you're Java calls this method In Applet3, the action() method does nothing more than call the applet's repaint() method, which tells Java that you want to redraw causes Java to call the paint() method, which very neatly displays the control's string. In the previous chapter, you learned to declare and define a number of different variable types, including You need only call the String class's valueOf() method, as shown in Listing Figure 6.7 : The Applet4 applet converts and displays an integer value. Listing 6.5 Applet4.java: The Source Code for Applet4. import java.applet.*; public class Applet4 extends Applet Tell Java that the program uses classes in the awt package. Tell Java that the program uses classes in the applet package. Derive the Applet4 class from Java's Applet class. Override the Applet class's paint() method. As you can see in Listing 6.5, the String class has a method called valueOf() that can convert The method's single argument is the value you want to convert, which can be any of Java's numerical data types. writing Java applets, you'll see other ways to perform I/O. In Chapter 4 "Object-Oriented Programming Concepts," you got a quick look at modular program By using top-down programming When programmers talk about subroutines, they usually mean program modules that return no value to your program. accomplish this task in a Java applet. Listing 12.1 Applet13.java: Printing Instructions in an Applet. import java.applet.*; public class Applet13 extends Applet performed by Applet13's paint() method, you might come up with something like "Draw of the applet that isolates the instruction-display task in its own function. Listing 12.2 Applet14.java: Placing the Instructions in a Function. import java.applet.*; public class Applet14 extends Applet The first is the paint() method, which Java calls whenever the applet's display area must be of the program calls paint(), but paint() calls functions that are lower in level. Specifically, a method is a function that is part of a class. methods of the Applet14 class. subroutine is a function that returns no value. Java function that returns no value to the calling function (paint(), in this case). There are two things you must do to use a function in a program. function, which means that you must write all the program instructions that make up the function, placing In Applet14, the DrawInstructions() function definition looks like The first line of Listing 12.3 tells Java the type of value returned from the function, the name of the method, you can see that Applet14 calls the DrawInstructions() function like this: This line tells Java that you want to execute the program code in the DrawInstructions() function access to g because it is the Graphics object that has the drawString() method. When you call a function, program after which the program returns to the line after the function call. Example: Using Functions to Return Values In Java, functions are the main way you can break up your programs into modules. used functions as subroutines, some types of functions return a value to the main program. this type of Java function before in this book. The String class' valueOf() method is one. The value You can assign a function's return value to a variable. that calculates a number and returns it to your program. ++value; value) and using functions to return values. the keyword void, functions that return values start with the keyword int, char, float or whatever type of return value you need. returns a value, Java's compiler will give you an error message. When you change the value of the argument in the function, you are Listing 12.5 APPLET15.JAVA: Using Functions in a Java Applet. import java.applet.*; public class Applet15 extends Applet Tell Java that the program uses classes in the awt package. Tell Java that the program uses classes in the applet package. Tell Java that the program uses the lang package's Math class. Derive the Applet15 class from Java's Applet class. Declare the class's data fields. Override the Applet class's init() method. Add the TextField object to the applet. Override the Applet class's paint() method. Override the Applet class's action() method. Tell Java to redraw the applet's display area. <applet code="Applet15.class" name="Applet15"> </applet> When you run Applet15, the program selects a random numeral from 1 to 100. You type your guesses into the box at the top of the applet. the program needs to be long in order to accommodate several different functions. program's flow, you can determine whether or not you understand how functions work. what the program does. You can see that some of the functions return values and others don't. return a value to the program (such as in CreateNumber()) and whether the function requires values using a top-down structure, your programs can organize code with functions that start off being general before program execution jumps back to the line after the line that called the function. return type other than void enables your programs to calculate a value and return the value to the calling Either type of function can have one or more arguments, which enable the program to pass values into the function. What is top-down programming?1. How do functions make top-down programming possible?2. Do all functions return values?3. How do you return a value from a function?6. How do you determine how to break a program up into functions?8. Modify Applet15 by adding a function that starts the game over each time the user guesses the That is, after the user guesses the number, the program should select a new random Name the program GuessApplet.java. Object-Oriented Programming Concepts Object-Oriented Programming Classes as Data Types❍ start exploring object-oriented programming (OOP) by briefly looking at the history of programming developed, you'll learn exactly what makes a programming language object-oriented. need for better ways to write these programs. High-level languages enable programmers to use English-like commands in their programs and to be less Today, the need for efficient programming methods is more important than ever. way is object-oriented programming. object encapsulates all the functions and data that it needs to get its job done. All these functions and data work together to define the object called a car. You can also think of a computer program as consisting of objects. Object-Oriented Programming You need to know only how to call the various functions (called methods in of an object in the Java programming language.) After you do this, you can control access to the data, forcing programs to retrieve or modify data only through the object's interface. How does this data-hiding differ from a structured-programming approach? structured program is to make the data global to the program, which gives any function access to it. Classes as Data Types An object is just an instance of a data type. creating an instance of the int data type. A class is like a data type in that it is the blueprint upon which When you need a new object in a program, you create a class, which is a kind of Then, in your program, you create an instance of the class. Classes are really nothing more than user-defined data types. For example, think again about the integer data type (int). After you define a new class, you can create many instances of the class. normally has full access to the class's methods and gets its own copy of the data members. This new class inherits all the data and methods from the tested base class. how all this works with Java in Chapter 14, "Classes.") Now, you only need to worry about testing the programming, you can think of a base class as a parent and a derived Although you won't actually start using Java classes until later in this book, this is a good time to look at constructing a class for a car object, you can think of direction, position, and speed as the class's data fields and the steering wheel, gas pedal, and brakes as representing the class's methods. The first step in creating an object is to define its class. class. You'll learn about Java classes in Chapter 14, "Classes." The base Car class might look like class Car In this base Car class, a car is defined by its direction (which way its pointed), position (where it's The data fields and methods are all encapsulated inside the class. Only the class's three methods can access the data fields. In short, Listing 4.1 not only shows what a class might look like, it class. data fields and methods from the Car base class. method called Pass(), but it also has the direction, position, and speed data fields, as well as all these data fields and methods exactly as if they were explicitly defined in Listing 4.2. In this way, the FastCar class implements the same functionality as the PassingCar() class, but it implements that functionality a little differently. and methods of the Car class. Java is an object-oriented language, meaning that it can not only enable you to organize your program start writing Java programs, much of what you read here will make more sense. What is top-down programming?1. How does a class relate to an object?5. List the object's data fields and2. Then, create a class for the object, using similar pseudocode to that used in Listing 4.1. Classes Classes and Objects Way back in Chapter 4 you got a general introduction to object-oriented programming concepts. Since then, you've been using various classes included as part of the Java language, but you plug up that hole in your understanding of Java and how it uses classes to create applets. Classes and Objects In Chapter 4 you learned that a class is the template for an object and that a class is a way to encapsulate both data (called fields in Java) and the functions (called methods) that operate on that data. class (called a superclass in Java). virtual methods that can be implemented differently in derived classes. you know about object-oriented programming towards creating Java classes. In this way, a class is equivalent to a data type such class, you must tell Java about the class's characteristics. Believe it or not, the preceding lines are a complete Java class. MyClass.java, you could even compile the class into a .CLASS file, although the file won't actually To create an object from a class, you type the class's name followed by For example, the line below creates an object from the MyClass class: Declaring Fields for a Class As I said, the MyClass example class doesn't do much yet. You declare fields for your class in much the same way you declare any variable in a program, by typing the data type of the field followed by the name of the field, like this: The above line declares a data field of type integer. much about how data fields are used with classes. the above line into the MyClass class definition, as shown in Listing 14.1. Listing 14.1 LST14_1.TXT: Adding a Data Field to a Class. Now you can see that myField is a data field of the MyClass class. A public data field can be accessed by any part of a program, inside or outside of the class in which it's A protected data field can only be accessed from within the class or from within a derived A private data field cannot even be accessed by a derived class. However, the class has no methods and so can do nothing The next step in defining the class, then, is to create methods. method, called a constructor, enables an object to initialize itself when it's created. public method (a method that can be accessed anywhere in a program) with the same name as the class. want to be able to create an object from the class anywhere in your program, and when you create an Example: Creating an Object by Calling a Constructor If you want to create an object from MyClass, you must supply an integer value that the class uses to create an object of the class like this: This line not only creates an object of the MyClass class, but also initializes the myField data field to 1. The first word in the line tells Java that myObject is going to be an object of the MyClass class. Other methods that you add to a class are just like the methods you've been writing in previous chapters. be called from outside the class, should be defined as public, methods that must be callable only from the class and its derived classes should be defined as protected, and methods that must be callable you can create a public method that can set the value for you. that returns the value of the field, as well, as shown in Listing 14.3. Listing 14.3 LST14_3.TXT: Adding a Method to the Class. Declare the class's myField data field. Set the data field to the value passed to SetField(). Return the value of the myField data field. According to the rules of strict object-oriented design, all class data Example: Using Classes in Applets Up till now, you've been writing applets using the classes already supplied as part of Java. see how to use your own classes in applets. work, but also help you to understand why you used Java's classes as you did. Type Listing 14.3 and save it to your CLASSES folder under the name MyClass.java. Type javac MyClass.java to compile the MyClass class. Type Listing 14.4 and save it as Applet19.java in your CLASSES folder. Listing 14.4 Applet19.java: An Applet That Uses the MyClass Class. import java.applet.*; public class Applet19 extends Applet g.drawString("The data field of the object", 30, 80); Tell Java that the program uses the awt package. Tell Java that the program uses the applet package. Tell Java that the program uses the MyClass class. Derive the Applet19 class from the Applet class. Declare an object of the MyClass class. Override the Applet class's init() method. Create an object of the MyClass class. Add the TextField object to the applet. Override the Applet class's paint() method. Override the Applet class's action() method. Type javac Applet19.java to compile the Applet19 applet. Applet19.class file in your CLASSES folder. Type Listing 14.5 and save the file as APPLET19.htmL.7. <applet code="Applet19.class" name="Applet19"> </applet> You're now ready to run the Applet19 applet, which uses the MyClass class. To run the program, type The applet's display area shows the current setting of MyClass's data field, myField. this setting by typing a new value into the text box and pressing Enter. Because the MyClass class is located in a different file than Applet19, you need to tell Java where to MyClass.class file, which you created when you compiled MyClass.java. This line tells Java that you'll be creating an object of the MyClass class and that the object will be You have to create the object, which Applet19 does After the above line executes, Java has created the object, which means you can now call the object's Objects of the MyClass class have only two Applet19 calls these methods in its paint() method, In the first line, Applet19 calls the object's SetField() method, whose single argument is the value to your applets. Specifically, you've been deriving your applet classes (i.e, Applet10, Applet11, and so on) from Java's Applet superclass. create a new similar class that does things a little differently. The new class will have all the you create a new applet, you start the applet's class with a line that looks something like this: public class MyApplet extends Applet First, Java insists that all applet classes be declared as public. Next in the line, you can see the class subclass of) the existing Applet class. As you've probably already figured out, Applet is a class that This class contains all the basic functionality you need to create an applet. You need only extend (there's that word again) the specifics of the class in order to create your own applet class. One thing you can do when you create a subclass is to add your own data fields and methods. example, when you derive your own applet class from Java's Applet class, although your class inherits tons of data fields and methods from the superclass, you'll undoubtedly need fields and methods not have I seen that before?) Obviously, when the fine programmers at Sun created the Applet class, they Take the MyClass class that you created earlier in this chapter (shown in Listing 14.3). want to create a new class that has a new data field called myNewField, as well as a constructor and methods for setting and retrieving the value of this new data field. The file containing the MySubClass class first imports the MyClass file, because Java will need the In the constructor, the class first calls Listing 14.7 APPLET20.JAVA: Using a Subclass in a Program. import java.applet.*; public class Applet20 extends Applet box to enter values for the original myField data field. Whenever you press Enter, the applet reads the values from the boxes and calls MySubClass's methods to set the new values and to retrieve the set values from the object. When you derive a new class from applet, you can override these the Applet class. For example, you know that, when Java starts up an applet, it calls the applet's init() method. how the Applet class defines init(): In the Applet class, the init() method does nothing at all. class from Applet, your applet class inherits all of Applet's data fields and methods. init() in your applet class, when Java starts your applet, it calls the Applet class's version of However, if you override init() in your class, Java is smart enough to example, you might need to pass a reference to the object as an argument in a method call. For example, inside an object that has the data field Of course, the SomeMethod() method would have been written to accept an object of this's type as If you've never done any object-oriented programming, it might take you a while to get used to using classes. programming to object-oriented programming (OOP). What is a class?1. How do classes help you to organize your programs?2. How do you create an object from a class?5. class. Add to TestClass a constructor that accepts a starting value for data1 as its single argument, and public methods for setting and retrieving the value of data1. integer data field called data2 (declared as private) and a public method called Modify Applet20 so that it creates an object of the TestSubClass class. Often in your programs, you'll want to store many values that are related in some way. give each player a variable in your program, as shown in Listing 13.1. Listing 13.1 Applet16.java: Using Variables to Track Scores.