Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 59 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
59
Dung lượng
1,91 MB
Nội dung
After you define a new class, you can create many instances of the class. Each instance (called an object) normally has full access to the class's methods and gets its own copy of the data members. Inheritance Inheritance enables you to create a class that is similar to a previously defined class, but one that still has some of its own properties. Consider a car-simulation program. Suppose that you have a class for a regular car, but now you want to create a car that has a high-speed passing gear. In a traditional program, you might have to modify the existing code extensively and might introduce bugs into code that worked fine before your changes. To avoid these hassles, you use the object-oriented approach: Create a new class by inheritance. This new class inherits all the data and methods from the tested base class. (You can control the level of inheritance with the public, private, and protected keywords. You'll see how all this works with Java in Chapter 14, "Classes.") Now, you only need to worry about testing the new code you added to the derived class. NOTE The designers of OOP languages didn't pick the word "inheritance" out of a hat. Think of how human children inherit many of their characteristics from their parents. But the children also have characteristics that are uniquely their own. In object-oriented programming, you can think of a base class as a parent and a derived class as a child. Polymorphism The last major feature of object-oriented programming is polymorphism. By using polymorphism, you can create new objects that perform the same functions as the base object but which perform one or more of these functions in a different way. For example, you may have a shape object that draws a circle on the screen. By using polymorphism, you can create a shape object that draws a rectangle instead. You do this by creating a new version of the method that draws the shape on the screen. Both the old circle-drawing and the new rectangle-drawing method have the same name (such as DrawShape()) but accomplish the drawing in a different way. Example: Encapsulation, Inheritance, and Polymorphism Although you won't actually start using Java classes until later in this book, this is a good time to look at OOP concepts in a general way. As an example, you'll extend the car metaphor you read earlier this chapter. In that section I described a car as an object having several characteristics (direction, position, and speed) and several means (steering wheel, gas pedal, and brakes) to act on those characteristics. In terms of 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. For now, you'll use pseudo-code to create a Car class. You'll learn about Java classes in Chapter 14, "Classes." The base Car class might look like Listing 4.1. Listing 4.1 LST4_1.TXT: The pseudocode for a Base Car Class. class Car { data direction; data position; data speed; method Steer(); method PressGasPedal(); method PressBrake(); } In this base Car class, a car is defined by its direction (which way its pointed), position (where it's located), and speed. These three data fields can be manipulated by the three methods Steer(), PressGasPedal(), and PressBrake(). The Steer() method changes the car's direction, whereas the PressGasPedal() and PressBrake() change the car's speed. The car's position is affected by all three methods, as well as by the direction and speed settings. The data fields and methods are all encapsulated inside the class. Moreover, the data fields are private to the class, meaning that they cannot be directly accessed from outside of 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 also shows how encapsulation works. Now, suppose you want to create a new car that has a special passing gear. To do this, you can use OOP inheritance to derive a new class from the Car base class. Listing 4.2 is the pseudocode for this new class. Listing 4.2 LST4_1.TXT: Deriving a New Class Using Inheritance. Class PassingCar inherits from Car { method Pass(); } You may be surprised to see how small this new class is. It's small because it implicitly inherits all the data fields and methods from the Car base class. That is, not only does the PassingCar class have a method called Pass(), but it also has the direction, position, and speed data fields, as well as the Steer(), PressGasPedal(), and PressBrake() methods. The PassingCar class can use all these data fields and methods exactly as if they were explicitly defined in Listing 4.2. This is an example of inheritance. The last OOP concept that you'll apply to the car classes is polymorphism. Suppose that you now decide that you want a new kind of car that has all the characteristics of a PassingCar, except that its passing gear is twice as fast as PassingCar's. You can solve this problem as shown in Listing 4.3. Listing 4.3 LST4_3.TXT: Using Polymorphism to Create a Faster Car. class FastCar inherits from PassingCar { method Pass(); } The FastCar class looks exactly like the original PassingCar class. However, rather than just inheriting the Pass() method, it defines its own version. This new version makes the car move twice as fast as PassingCar's Pass() method does (the code that actually implements each method is not shown). In this way, the FastCar class implements the same functionality as the PassingCar() class, but it implements that functionality a little differently. NOTE Because the FastCar class inherits from PassingCar, which itself inherits from Car, a FastCar also inherits all the data fields and methods of the Car class. There are ways that you can control how inheritance works (using the public, protected, and private keywords), but you won't get into that until much later in this book. Summary Java is an object-oriented language, meaning that it can not only enable you to organize your program code into logical units called objects, but also that you can take advantage of encapsulation, inheritance, and polymorphism. Learning OOP, however, can be a little tricky. If you're a novice programmer, this chapter has probably left you confused. If so, read on to learn more about the Java language. Once you start writing Java programs, much of what you read here will make more sense. After finishing this part of the book, you might want to reread this chapter and so reinforce any concepts that may be shady now. Review Questions 1. What is top-down programming? 2. What's the advantage of top-down programming? 3. How is OOP better than top-down programming? 4. What are the two main elements of a class? 5. How does a class relate to an object? 6. What are the three major concepts used in OOP? 7. Define each of these three concepts. Review Exercises 1. Take an everyday task such as making a cake or driving a car and break the task down into a top- down "program." Try to create three levels of detail. 2. Consider a real-world object such as a stereo receiver or an oven. List the object's data fields and functions. Then, create a class for the object, using similar pseudocode to that used in Listing 4.1. Chapter 5 Constants and Variables CONTENTS ● Constants ● Variables ● Naming Constants and Variables ● Example: Creating Your Own Identifiers ● Data Types ❍ Integer Values ❍ Floating-Point Values ❍ Character Values ❍ Boolean Values ● Variable Scope ❍ Example: Determining a Variable's Scope ● Summary ● Review Questions ● Review Exercises If there's one thing that every computer program has in common, it's that they always process data input and produce some sort of output based on that data. And because data is so important to a computer program, it stands to reason that there must be plenty of different ways to store data so that programs can do their processing correctly and efficiently. In order to keep track of data, programs use constants and variables. In this chapter, you discover what constants and variables are, as well as learn to use them in the Java language. Constants If you think about the term "constant" for a few moments, you might conclude that constants must have something to do with data that never changes. And your conclusion would be correct. A constant is nothing more than a value, in a program, that stays the same throughout the program's execution. However, while the definition of a constant is fairly simple, constants themselves can come in many different guises. For example, the numeral 2, when it's used in a line of program code, is a constant. If you place the word "Java" in a program, the characters that comprise the word are also constants. In fact, these constant characters taken together are often referred to as a string constant. NOTE To be entirely accurate, I should say that text and numerals that are placed in program code are actually called literals, because the value is literally, rather than symbolically, in the program. If this literal and symbolic stuff is confusing you, you'll probably have it figured out by the end of this chapter. For now, just know that I'm lumping literals in with constants to simplify the discussion. Such values as the numeral 2 and the string constant "Java" are sometimes called hard-coded values because the values that represent the constants are placed literally in the program code. For example, suppose you were writing a program and wanted to calculate the amount of sales tax on a purchase. Suppose further that the total purchase in question is $12.00 and the sales tax in your state is 6 percent. The calculation that'll give you the sales tax would look like this: tax = 12 * .06; Suppose now that you write a large program that uses the sales tax percentage in many places. Then, after you've been happily using your program for a few months, the state suddenly decides to raise the sales tax to seven percent. In order to get your program working again, you have to go through every line of code, looking for the .06 values that represent the sales tax and changing them to .07. Such a modification can be a great deal of work in a large program. Worse, you may miss one or two places in the code that need to be changed, leaving your program with some serious bugs. To avoid these situations, programmers often use something called symbolic constants, which are simply words that represent values in a program. In the case of your sales tax program, you could choose a word like SALESTAX (no spaces) to represent the current sales tax percentage for your state. Then, at the beginning of your program, you set SALESTAX to be equal to the current state sales tax. In the Java language, such a line of program code might look like this: final float SALESTAX = 0.06; In the preceding line, the word final tells Java that this data object is going to be a constant. The float is the data type, which, in this case, is a floating point. (You'll learn more about data types later in this chapter.) The word SALESTAX is the symbolic constant. The equals sign tells Java that the word on the left should be equal to the value on the right, which, in this case, is 0.06. After defining the symbolic constant SALESTAX, you can rewrite any lines that use the current sales tax value to use the symbolic constant rather than the hard-coded value. For example, the calculation for the sales tax on that $12.00 purchase might now look something like this: tax = 12 * SALESTAX; TIP In order to differentiate symbolic constants from other values in a program, programmers often use all uppercase letters when naming these constants. Now, when your state changes the sales tax to 7 percent, you need only change the value you assign to the symbolic constant and the rest of the program automatically fixes itself. The change would look like this: final float SALESTAX = 0.07; Variables If constants are program values that cannot be changed throughout the execution of a program, what are variables? Variables are values that can change as much as needed during the execution of a program. Because of a variable's changing nature, there's no such thing as a hard-coded variable. That is, hard- coded values in a program are always constants (or, more accurately, literals). Why do programs need variables? Think back to the sales tax program from the previous section. You may recall that you ended up with a program line that looked like this: tax = 12 * SALESTAX; In this line, the word tax is a variable. So, one reason you need variables in a program is to hold the results of a calculation. In this case, you can think of the word tax as a kind of digital bucket into which the program dumps the result of its sales tax calculation. When you need the value stored in tax, you can just reach in and take it out-figuratively speaking, of course. As an example, to determine the total cost of a $12.00 purchase, plus the sales tax, you might write a line like this: total = 12 + tax; In this line, the word total is yet another variable. After the computer performs the requested calculation, the variable total will contain the sum of 12 and whatever value is stored in tax. For example, if the value 0.72 is stored in tax, after the calculation, total would be equal to 12.72. Do you see another place where a variable is necessary? How about the hard-coded value 12? Such a hard-coded value makes a program pretty useless because every person that comes into your store to buy something isn't going to spend exactly $12.00. Because the amount of each customer's purchase will change, the value used in your sales tax calculation must change, too. That means you need another variable. How about creating a variable named purchase? With such a variable, you can rewrite the calculations like this: tax = purchase * SALESTAX; total = purchase + tax; Now you can see how valuable variables can be. Every value in the preceding lines is represented by a variable. (Although you're using SALESTAX as a symbolic constant, because of Java's current lack of true constants, it's really a variable, too.) All you have to do to get the total to charge your customer is plug the cost of his purchase into the variable purchase, something you'll see how to do in Chapter 6 "Simple Input and Output." Math-savvy readers may have already figured that the preceding two lines can be easily simplified into one, like this: total = purchase + (purchase * SALESTAX); This revised line of code, however, is not as easy to understand as the original two lines were. In programming, you must constantly decide between longer, simpler code and shorter, more complex code. I tend to go for the longer, easy-to-understand approach, except when the longer code might bog down the program. Naming Constants and Variables The first computer languages were developed by mathematicians. For that reason, the calculations and the variables used in those calculations were modeled after the types of equations mathematicians were already accustomed to working with. For example, in the old days, the lines in your tax program might have looked like this: a = b * c; d = b + a; As you can see, this type of variable-naming convention left a lot to be desired. It's virtually impossible to tell what type of calculations are being performed. In order to understand their own programs, programmers had to use tons of comments mixed in with their source code so they could remember what the heck they were doing from one programming session to the next. Such a section of source code in Java might look like Listing 5.1. Listing 5.1 LST5_1.TXT: An Example of Mathematician's Variables. // Calculate the amount of sales tax. a = b * c; // Add the sales tax to the purchase amount. d = b + a; Although adding comments to the program lines helps a little, the code is still pretty confusing, because you don't really know what the variables a, b, c, and d stand for. After a while (probably when mathematicians weren't the only programmers), someone came up with the idea of allowing more than one character in a variable name, which would enable the programmer to create mathematical [...]... Table 5 .2 summarizes Java' s various data types Take some time now to look over the table and make sure you understand how the data types differ from each other You might also want to think of ways you might use each data type in an actual program Table 5 .2 Summary of Java' s Data Types Type Value byte - 128 to 127 short - 32, 768 to 32, 767 int -2, 147,483,648 to 2, 147,483,647 long Huge float -3.4 028 23e38... in a Java program The e2 in the second example is the equivalent of writing x 1 02 and is a short form of scientific notation that's often used in programming languages NOTE If you're not familiar with scientific notation, the value 3.4 028 23 x 10 38 is equal to 3.4 028 23 times a number that starts with a 1 and is followed by 38 zeroes Computer languages shorten this scientific notation to 3.4 028 23e38... Applet2 .java (You can copy the source code from the CD-ROM, if you like, and thus save on typing Of course, you won't learn as much that way.) Then compile the source code (type javac Applet2 .java at the MS-DOS prompt), which gives you the Applet2.class file Next, create a new HTML document from the one shown in Listing 6 .2, changing all instances of Applet1 to Applet2 You can then run Applet2 by typing... be in the range from -1.7976931348 623 2 x 10 308 to 1.7976931348 623 2 x 10 308 and is declared like this: double identifier; or double identifier = value; Floating-point values of the double type are written exactly as their float counterparts, except you use an upper- or lowercase D as the suffix, rather than an F Here's a few examples: 3.14d 344 .23 456D 3.4 423 456e2d TIP When using floating-point numbers... 100 The next biggest type of Java integer is short A variable declared as short can hold a value from 32, 768 to 32, 767 You declare a short value like this: short identifier; or short identifier = value; In the preceding line, value can be any value from - 32, 768 to 32, 767, as described previously In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values Next in the integer... For example, looking back at Figure 5.1, a variable that's defined in Block 1 is accessible in not just Block 1, but also in Block 2 and Block 3 However, a variable defined inside Block 2 is accessible only in Block 2, because such a variable goes into scope at the start of Block 2 and goes out of scope at the end of Block 2 If you're a little confused, the following example ought to clear things up Example: ... Windows You might, for example, see a number of edit controls in a dialog box Listing 4.3 shows how to include a TextField control in your applet Figure 6.5 shows the Applet2 applet in action 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. awt.*; import java. applet.*; public class Applet2 extends Applet { TextField... move a byte value, which consumes only eight bits of memory, much faster than an int value, which, in Java, is four times as large In Java, you declare a byte value like this: byte identifier; In the preceding line, byte is the data type for the value, and identifier is the variable's name You can also simultaneously declare and assign a value to a variable like this: byte count = 100; After Java executes... Listing 6.1 Applet1 .java: An Applet That Displays a Single Line of Text import java. awt.*; import java. applet.*; public class Applet1 extends Applet { public void paint(Graphics g) { g.drawString("Hello from Java! ", 60, 75); } } 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... Types Type Value byte - 128 to 127 short - 32, 768 to 32, 767 int -2, 147,483,648 to 2, 147,483,647 long Huge float -3.4 028 23e38 to 3.4 028 23e38 double -1.7976931348 623 2e308 to 1.7976931348 623 2e308 char Symbols used in text boolean True or false Variable Scope When you write your Java programs, you can't just declare your variables willy-nilly all over the place You first have to consider how and where you . program. Table 5 .2 Summary of Java& apos;s Data Types. Type Value byte - 128 to 127 short - 32, 768 to 32, 767 int -2, 147,483,648 to 2, 147,483,647 long Huge float -3.4 028 23e38 to 3.4 028 23e38 double. the value 3.4 028 23 x 10 38 is equal to 3.4 028 23 times a number that starts with a 1 and is followed by 38 zeroes. Computer languages shorten this scientific notation to 3.4 028 23e38. The second. line, value can be any value from - 32, 768 to 32, 767, as described previously. In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values. Next in the integer data