giáo trình Java By Example phần 6

giáo trình Java By Example phần 6

Lượt xem: 41,319Lượt tải: 2Số trang: 66

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 the rules given, the following are valid in a Java following are not valid in a Java to change from one program run to another, the number of vehicles that the garage can hold would In this line, the keyword int the data type, which is has eight different data types, all of which kinds of values in a 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 values, which Java does not support, can hold only positive Java, you declare a byte value like this: In the preceding line, byte is the data type for the value, and is the Java executes the preceding line, your program will have a variable named count that in the integer data types is int, which can hold a value from to 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 do you know which integer data type to use in your integer values can hold only whole numbers, the data types can hold values 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 of the preceding values are and you can use either form in a Java second type of data, double, a value, which is a much When using numbers in your programs, the same in your programs, you'll need a way to represent character values rather than just order to provide storage for character values, Java features the char data type, which is 16 the size of the char data type has little to do with the values it can 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 you might write something like the following in your Java you want to use these in your program's data, you must also you might need to know whether a part of your program executed use Boolean values, which are in Java by the boolean data 5.2 Java's various data use each data type in an actual 5.2 Summary of Java's Data you write your Java programs, you can't just declare your variables all over the about that just yet.) program blocks include things like classes, and loops, As you'll see when you start writing Java all you've written the small Java program shown in Listing know much about writing Java class Block1 extends = = 100; Now look at the variables being used in this 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 you tried to compile this program, you'd see that this line creates an error message, as declare variables that you need in many places, so that they are in scope in the entire you'll have lots of variables that you use only inside one program program by being sure to declare these types of variables only in the blocks in like all many data types that you can use for constants and variables in your the eight data types used in you need to write a Java program that an paycheck for a 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 Text in an Applet In the previous chapter, you learned how you can store various types of values in your Java Text in an of Java's to display a single line of 6.1 An Applet That Displays a Single Line of class Applet1 extends Java that the program uses classes in the awt Java that the program uses classes in the applet the Applet1 class from Java's Applet the Applet class's paint() 6.2 : When you run the Applet1 applet, you'll see a single line of text Creating and Running 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 javac to compile the Applet1 make sure you typed the command line javac the compiler finishes, you'll have the file in your CLASSES 6.3 : The file must compile with no Listing 6.2 and save it as an ASCII file to your CLASSES calls paint() whenever the applet's display area (or paint() method always gets called when the applet first You run the applet, Java when the applet appears, and paint() calls which displays the text is a method of the Graphics class to the paint() method and that object is called g. tells Java to call the g object's which are values that you need to send to the 6.4 : Here, Applet1 displays the text at position a control of the TextField class in your 6.5 : The Applet2 applet displays an area in which you can 6.3 Getting Input from the class Applet2 extends Java that the program uses classes in the awt Java that the program uses classes in the applet the Applet2 class from Java's Applet textField as an object of the TextField the Applet class's init() the TextField object to the applet's run the Applet2 applet yourself, you'll need to type and save the source code, naming at the MS-DOS prompt), which gives you the of the TextField class, which 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 class, but textField hasn't yet been assigned a 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 creating the control and adding it to the applet, the control will appear when Java In the Applet2 applet, you can type all you like in the TextField control, but how do you get the the steps below to create Applet3, a new Type Listing 6.4 and save it in the CLASSES folder as an ASCII 6.4 Source Code for the Applet3 class Applet3 extends Java that the program uses classes in the awt Java that the program uses classes in the applet the Applet3 class from Java's Applet textField as an object of the TextField the Applet class's init() the TextField object to the applet's the Applet class's paint() the Applet class's action() javac to compile the Applet3 you typed the command line javac you run Applet3, go ahead and type some text into the TextField the text appears in the applet's display area, right below the control (Figure 6.6 : Applet3 can display the text you type into the TextField you look at the Applet3 program code, you can see that you've added a paint() 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 text strings.) You can see in this line that calls this method In Applet3, the action() nothing more than call the applet's repaint() method, which tells Java that you want to Java to call the paint() method, which very neatly displays the control's the previous chapter, you learned to declare and define a number of different variable types, need only call the String class's valueOf() method, as shown in 6.7 : The Applet4 applet converts and displays an integer 6.5 The Source Code for class Applet4 extends Java that the program uses classes in the awt Java that the program uses classes in the applet the Applet4 class from Java's Applet the Applet class's paint() you can see in Listing 6.5, the String class has a method called valueOf() that can method's single argument is the value you want to convert, which can be any of Java's numerical data Java applets, you'll see other ways to perform I/O. In Chapter 4 you got a quick look at modular using top-down talk about they usually mean program modules that return no value to your this task in a Java 12.1 Printing in an class Applet13 extends by paint() method, you might come up with something like "Draw of the applet that isolates the task in its own 12.2 Placing the in a class Applet14 extends 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 a method is a function that is part of a of the Applet14 is a function that returns no function that returns no value to the calling function (paint(), in this are two things you must do to use a function in a which means that you must write all the program that make up the function, Applet14, the function looks like The first line of Listing 12.3 tells Java the type of value returned from the function, the name of you can see that Applet14 calls the function like line tells Java that you want to execute the program code in the to g because it is the Graphics object that has the you call a function, which the program returns to the line after the function Using Functions to Return Values In Java, functions are the main way you can break up your programs into functions as some types of functions return a value to the main type of Java function before in this book. The String class' valueOf() method is one. The value You can assign a return value to a a number and returns it to your and using functions to return keyword void, functions that return values start with the keyword int, char, float or of return value you a value, Java's compiler will give you an error you change the value of the argument in the function, you 12.5 Using Functions in a Java class Applet15 extends Java that the program uses classes in the awt Java that the program uses classes in the applet Java that the program uses the lang package's Math the Applet15 class from Java's Applet the class's data the Applet class's init() the TextField object to the the Applet class's paint() the Applet class's action() Java to redraw the applet's display 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 program needs to be long in order to several different flow, you can determine whether or not you how functions the program does. You can see that some of the functions return values and others a value to the program (such as in and whether the function requires a top-down your programs can organize code with functions that start off being program execution jumps back to the line after the line that called the type other than void enables your programs to calculate a value and return the value to the type of function can have one or more which enable the program to into the is top-down do functions make top-down all functions return do you return a value from a do you determine how to break a program up into 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 the program as Data Types❍ start exploring (OOP) by briefly looking at the history of you'll learn exactly what makes a language for better ways to write these languages enable to use commands in their programs and to be the need for efficient methods is more important than ever. way is 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 of need to know only how to call the various functions (called methods in of an object in the Java After you do this, you can control access to the programs to retrieve or modify data only through the object's does this differ from a program is to make the data global to the program, which gives any function access to as Data Types An object is just an instance of a data an instance of the int data type. A class is like a data type in that it is the blueprint upon 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 are really nothing more than data example, think again about the integer data type you define a new class, you can create many instances of the has full access to the class's methods and gets its own copy of the data new class inherits all the data and methods from the tested base all this works with Java in Chapter 14, Now, you only need to worry about testing you can think of a base class as a parent and a you won't actually start using Java classes until later in this book, this is a good time to look a class for a car object, you can think of position, and speed as the class's and the steering wheel, gas pedal, and brakes as the class's first step in creating an object is to define its learn about Java classes in Chapter 14, The base Car class might look 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 inside the the class's can access the data short, Listing 4.1 not only shows what a class might look like, fields and methods from the Car base called Pass(), but it also has the position, and speed data fields, as well as all these data fields and methods exactly as if they were defined in Listing 4.2. In this way, the FastCar class the same as the but it that a little methods of the Car is an language, meaning that it can not only enable you to organize your writing Java programs, much of what you read here will make more is top-down does a class relate to an the object's data fields create a class for the object, using similar to that used in Listing and back in Chapter 4 you got a general to then, you've been using various classes included as part of the Java language, but you plug up that hole in your of Java and how it uses classes to create and Chapter 4 you learned that a class is the template for an object and that a class is a way to data (called fields in Java) and the functions (called methods) that operate on that (called a in methods that can be in derived know about towards creating Java this way, a class is to a data type you must tell Java about the class's it or not, the preceding lines are a complete Java you could even compile the class into a .CLASS file, although the file won't 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 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 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 about how data fields are used with above line into the MyClass class as shown in Listing 14.1 Adding a Data Field to a 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 the class has no methods and so can do next step in defining the class, then, is to create called a enables an object to itself when it's method (a method that can be accessed anywhere in a program) with the same name as to be able to create an object from the class anywhere in your program, and when you create Creating an Object by Calling a 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 line not only creates an object of the MyClass class, but also 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 methods that you add to a class are just like the methods you've been writing in previous 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 and methods that must be 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 Adding a Method to the the class's myField data the data field to the value passed to the value of the myField data to the rules of strict design, all class Using Classes in till now, you've been writing applets using the classes already supplied as part of Java. see how to use your own classes in but also help you to why you used Java's classes as you did. Type Listing 14.3 and save it to your CLASSES folder under the name javac to compile the MyClass Listing 14.4 and save it as in your CLASSES 14.4 An Applet That Uses the MyClass class Applet19 extends data field of the object", 30, 80); Tell Java that the program uses the awt Java that the program uses the applet Java that the program uses the MyClass the Applet19 class from the Applet an object of the MyClass the Applet class's init() an object of the MyClass the TextField object to the the Applet class's paint() the Applet class's action() javac to compile the Applet19 file in your CLASSES Listing 14.5 and save the file as 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, setting by typing a new value into the text box and pressing the MyClass class is located in a different file than Applet19, you need to tell Java where file, which you created when you compiled 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 the above line executes, Java has created the object, which means you can now call the of the MyClass class have only calls these methods in its paint() the first line, Applet19 calls the object's method, whose single argument is the value to your you've been deriving your applet classes (i.e, Applet10, Applet11, and so on) from Java's Applet a new similar class that does things a little new class will have all the you create a new applet, you start the applet's class with a line that looks something like class MyApplet extends Java insists that all applet classes be declared as in the line, you can see the of) the existing Applet class. As you've probably already figured out, Applet is a class that This class contains all the basic you need to create need only extend (there's that word again) the specifics of the class in order to create your own applet thing you can do when you create a subclass is to add your own data fields and when you derive your own applet class from Java's Applet class, although your class of data fields and methods from the you'll need fields and methods not have I seen that before?) when the fine at Sun created the Applet class, they Take the MyClass class that you created earlier in this chapter (shown in Listing to create a new class that has a new data field called as well as a for setting and the value of this new data file the class first imports the MyClass file, because Java will need the In the the class first 14.7 Using a Subclass in a class Applet20 extends to enter values for the original myField data you press Enter, the applet reads the values from the boxes and methods to set the new values and to retrieve the set values from the you derive a new class from applet, you can override these the Applet example, you know that, when Java starts up an applet, it calls the applet's init() the Applet class defines the Applet class, the init() method does nothing at from Applet, your applet class inherits all of Applet's data fields and in your applet class, when Java starts your applet, it calls the Applet class's version if you override init() in your class, Java is smart enough 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 method would have been written to accept an object of this's type as If you've never done any it might take you a while to get used to to is a do classes help you to organize your do you create an object from a to TestClass a that accepts a starting value for data1 as its single public methods for setting and the value of data field called data2 (declared as private) and a public method Applet20 so that it creates an object of the 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 Using Variables to Track Scores.