1. Trang chủ
  2. » Công Nghệ Thông Tin

Java All-in-One Desk Reference For Dummies phần 4 docx

89 204 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Book III Chapter 1 Understanding Object-Oriented Programming Understanding Objects 241 Attribute Object 1 Object 2 Number One Two Color Red Blue The type of an object determines what attributes the object has. Thus, all objects of a particular type have the same attributes. However, they don’t necessarily have the same values for those attributes. In this example, all Fish have attributes named Number and Color, but the two Fish objects have different values for these attributes. The combination of the values for all the attributes of an object is called the object’s state. Unlike its identity, an object’s state can and usually does change over its lifetime. For example, some fish can change colors. The total sales for a customer changes each time the customer buys another product. The grade point average for a student changes each time a new class grade is recorded. And the address and phone number of an employee changes if the employee moves. Here are a few more interesting details about object state: ✦ Some of the attributes of an object are publicly known, but others can be private. The private attributes may be vital to the internal operation of the object, but no one outside of the object knows they exist. They’re like your private thoughts: They affect what you say and do, but nobody knows them but you. ✦ In Java, the state of an object is represented by class variables, which are called fields. A public field is a field that’s declared with the public keyword so the variable can be visible to the outside world. Objects have behavior Another characteristic of objects is that they have behavior, which means they can do things. Like state, the specific behavior of an object depends on its type. But unlike state, the behavior isn’t different for each instance of a type. For example, suppose all the students in a classroom have calculators of the same type. Ask them all to pull out the calculators and add two numbers — any two numbers of their choosing. All the calculators display a different number, but they all add the same. In other words, they all have a different state, but the same behavior. Another way to say that objects have behavior is to say they provide serv- ices that can be used by other objects. You’ve already seen plenty examples of objects that provide services to other objects. For example, objects cre- ated from the NumberFormat class provide formatting services that turn numeric values into nicely formatted strings like $32.95. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 241 The Life Cycle of an Object 242 In Java, the behavior of an object is provided by its methods. Thus, the format method of the NumberFormat class is what provides the format- ting behavior for NumberFormat objects. Here are a few other notable points about object behavior: ✦ The interface of a class is the set of methods and fields that the class makes public so other objects can access them. ✦ Exactly how an object does what it does can and should be hidden within the object. Someone who uses the object needs to know what the object does, but doesn’t need to know how it works. If you later find a better way for the object to do its job, you can swap in the new improved version without anyone knowing the difference. The Life Cycle of an Object As you work with objects in Java, understanding how objects are born, live their lives, and die is important. This topic is called the life cycle of an object, and it goes something like this: ✦ Before an object can be created from a class, the class must be loaded. To do that, the Java runtime locates the class on disk (in a .class file) and reads it into memory. Then, Java looks for any static initializers that initialize static fields — fields that don’t belong to any particular instance of the class, but rather belong to the class itself and are shared by all objects created from the class. A class is loaded the first time you create an object from the class or the first time you access a static field or method of the class. For example, when you run the main method of a class, the class is initialized because the main method is static. ✦ An object is created from a class when you use the new keyword. To initialize the class, Java allocates memory for the object and sets up a reference to the object so the Java runtime can keep track of it. Then, Java calls the class constructor, which is like a method but is called only once, when the object is created. The constructor is responsible for doing any processing required to initialize the object, such as initializing variables, opening files or databases, and so on. ✦ The object lives its life, providing access to its public methods and fields to whoever wants and needs them. ✦ When it’s time for the object to die, the object is removed from memory and Java drops its internal reference to it. You don’t have to destroy objects yourself. A special part of the Java runtime called the garbage collector takes care of destroying all objects when they are no longer in use. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 242 Book III Chapter 1 Understanding Object-Oriented Programming Working with Related Classes 243 Working with Related Classes So far, most of the classes you’ve seen in this book have created objects that stand on their own, each being a little island unto itself. However, the real power of object-oriented programming lies in its ability to create classes that describe objects that are closely related to each other. For example, baseballs are similar to softballs. Both are specific types of balls. They both have a diameter and a weight. And both can be thrown, caught, or hit. However, they have different characteristics that cause them to behave differently when thrown, caught, or hit. If you’re creating a program that simulated the way baseballs and softballs work, you need a way to represent these two types of balls. One option is to create separate classes to represent each type of ball. These classes are sim- ilar, so you can just copy most of the code from one class to the other. Another option is to use a single class to represent both types of balls. Then, you pass a parameter to the constructor to indicate whether an instance of the class behaves like a baseball or like a softball. However, Java has two object-oriented programming features that are designed specifically to handle classes that are related like this: inheritance and interfaces. I briefly describe these features in the following sections. Inheritance Inheritance is an object-oriented programming technique that lets you use one class as the basis for another. The existing class is called the base class, superclass, or parent class, and the new class that’s derived from it is called the derived class, subclass, or child class. When you create a subclass, the subclass is automatically given all the meth- ods and fields defined by its superclass. You can use these methods and fields as is, or you can override them to alter their behavior. In addition, you can add additional methods and fields that define data and behavior that’s unique to the subclass. You could use inheritance to solve the baseball/softball problem from the previous section by creating a class named Ball that provides the basic features of all types of balls, and then using it as the base class for separate classes named BaseBall and SoftBall. Then, these classes could over- ride the methods that need to behave differently for each type of ball. One way to think of inheritance is as a way to implement is-a-type-of relation- ships. For example, a softball is a type of ball, as is a baseball. Thus, inheritance is an appropriate way to implement these related classes. For more informa- tion about inheritance, see Book III, Chapter 4. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 243 Designing a Program with Objects 244 Interfaces An interface is a set of methods and fields that a class must provide to imple- ment the interface. The interface itself is simply a set of public method and field declarations that are given a name. Note that the interface itself doesn’t provide any code that implements those methods. Instead, it just provides the declarations. Then, a class that implements the interface provides an implementation for each of the methods the interface defines. You could use an interface to solve the baseball/softball problem by creating an interface named Ball that specifies all the methods and fields that a ball should have. Then, you could create the SoftBall and BaseBall classes so that they both implement the Ball interface. Interfaces are closely related to inheritance, but have two key differences: ✦ The interface itself doesn’t provide code that implements any of its methods. An interface is just a set of method and field signatures. In con- trast, a base class can provide the implementation for some or all of its methods. ✦ A class can have only one base class. However, a class can implement as many interfaces as necessary. You find out about interfaces in Book III, Chapter 5. Designing a Program with Objects An object-oriented program usually isn’t just a single object. Instead, it’s a group of objects that work together to get a job done. The most important part of developing an object-oriented program is designing the classes that are used to create the program’s objects. The basic idea is to break a large problem down into a set of classes that are each manageable in size and complexity. Then, you write the Java code that implements those classes. So, the task of designing an object-oriented application boils down to decid- ing what classes the application requires and what the public interface to each of those classes are. If you plan your classes well, implementing the application is easy. But if you poorly plan your classes, you’ll have a hard time getting your application to work. One common way to design object-oriented applications is to divide the application into several distinct layers or tiers that provide distinct types of functions. The most common is a three-layered approach, as shown in Figure 1-1. Here, the objects of an application are split up into three basic layers: 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 244 Book III Chapter 1 Understanding Object-Oriented Programming Diagramming Classes with UML 245 ✦ Presentation: The objects in this layer handle all the direct interaction with users. For example, the HTML pages in a Web application go in this layer, as do the Swing page and frame classes in a GUI-based application (I cover Swing in Book VI). ✦ Logic: The objects in this layer represent the core objects of the applica- tion. For a typical business-type application, this layer includes objects that represent business entities such as customer, products, orders, suppliers, and the like. This layer is sometimes called the business rules layer because the objects in this layer are responsible for carrying out the rules that govern the application. ✦ Database: The objects in this layer handle all the details of interacting with whatever form of data storage is used by the application. For exam- ple, if the data is stored in a SQL database, the objects in this layer handle all of the SQL. Diagramming Classes with UML Since the very beginning of computer programming, programmers have loved to create diagrams of their programs. Originally, they drew flowcharts that graphically represented a program’s procedural logic. Flowcharts were good at diagramming procedures, but they were way too detailed. When the Structured Programming craze hit in the 1970s and pro- grammers started thinking about the overall structure of their programs, they switched from flowcharts to structure charts , which illustrated the organizational relationships among the modules of a program or system. AccountUpdater Account AccountDB Presentation layer Logic layer Database layer ReportCreator Customer CustomerDB Figure 1-1: Three- layered design. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 245 Diagramming Classes with UML 246 Now that object-oriented programming is the thing, programmers draw class diagrams to illustrate the relationships among the classes that make up an application. For example, the simple class diagram shown in Figure 1-2 shows a class diagram for a simple system that has four classes. The rectangles rep- resent the classes themselves, and the arrows represent the relationships among the classes. You can draw class diagrams in many ways. To add some consistency to their diagrams, most programmers use a standard called UML, which stands for Unified Modeling Language. The class diagram in Figure 1-2 is an example of a simple UML diagram, but UML diagrams can get much more complicated than this example. The following sections describe the details of creating UML class diagrams. Note that these sections don’t even come close to explaining all the features of UML. I include just the basics of creating UML class diagrams so that you can make some sense of UML diagrams when you see them, and so that you know how to draw simple class diagrams to help you design the class struc- ture for your applications. If you’re interested in digging deeper into UML, check out UML 2 For Dummies by Michael Jesse Chonoles and James A. Schardt (Wiley). Drawing classes The basic element in a class diagram is a class. In UML, each class is drawn as a rectangle. At the minimum, the rectangle must include the class name. However, you can subdivide the rectangle into two or three compartments that can contain additional information about the class, as shown in Figure 1-3. «abstract» Person Staff Database Student Figure 1-2: A simple class diagram. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 246 Book III Chapter 1 Understanding Object-Oriented Programming Diagramming Classes with UML 247 The middle compartment of a class lists the class variables, while the bottom compartment lists the class methods. The name of each variable or method can be preceded by a visibility indicator, which can be one of the symbols listed in Table 1-1. In actual practice, omiting the visibility indicator and listing only those fields or methods that have public visibility is common. Table 1-1 Visibility Indicators for Class Variables and Methods Indicator Description + Public - Private # Protected If you want, you can include type information for variables as well as for methods and parameters. The type of a variable is indicated by following the variable name with a colon and the type: connectionString: String A method’s return type is indicated in the same way: getCustomer(): Customer Parameters are listed within the parentheses, and both the name and type are listed. For example: getCustomer(custno: int): Customer Note: Omitting the type and parameter information from UML diagrams is common. CustomerDB +connectionString +connectionStatus +getCustomer +updateCustomer +deleteCustomer +addCustomer +getCustomerList Figure 1-3: A class. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 247 Diagramming Classes with UML 248 Interfaces are drawn pretty much the same as classes, but the class name is preceded by the word interface: «interface» ProductDB Note: The word interface is enclosed within a set of double-left and double- right arrows. These arrows aren’t just two less-than or greater-than symbols typed in a row; they’re a special symbol. Fortunately, this symbol is a stan- dard part of the ASCII character set. You can access them in Microsoft Word via the Insert Symbol command. Drawing arrows Besides rectangles to represent classes, class diagrams also include arrows to represent relationships among classes. UML uses a variety of different types of arrows, as I describe in the following paragraphs. A solid line with a hollow closed arrow at one end represents inheritance: The arrow points to the base class. A dashed line with a hollow close arrow at one end indicates that a class implements an interface: The arrow points to the interface. A solid line with an open arrow indicates an association: An association simply indicates that two classes work together. It may be that one of the classes creates objects of the other class, or that one class requires an object of the other class to perform its work. Or, perhaps instances of one class contain instances of the other class. You can add a name to an association arrow to indicate its purpose. For example, if an association arrow indicates that instances of one class create objects of another class, you can place the word Creates next to the arrow. 19_58961X bk03ch01.qxd 3/29/05 3:39 PM Page 248 Chapter 2: Making Your Own Classes In This Chapter ߜ Creating your own class ߜ Looking at the pieces of a class declaration ߜ Finding out about class fields ߜ Constructing constructors ߜ Adding methods to your classes ߜ Using the this keyword O kay, class, it’s time to learn how to create your own classes. In this chapter, you discover the basics of creating classes in Java. All Java programs are classes, so you’ve already seen many examples of classes. For example, you’ve seen class headers such as public class GuessingGame and static methods such as public static void main. Now, in this chapter, I show you how to create programs that have more than one class. Declaring a Class All classes must be defined by a class declaration that provides the name for the class and the body of the class. Here’s the most basic form of a class declaration: [public] class ClassName {class-body} The public keyword indicates that this class is available for use by other classes. Although it is optional, you usually include it on your class declara- tions. After all, the main reason you write class declarations is so that other classes can create objects from the class. Find out more about using the public keyword in the section “Where classes go” later in this chapter. In later chapters of this book, you find out about some additional elements that can go in a class declaration. The format I’m describing here is just the basic format, which you use to create basic classes. 20_58961x bk03ch02.qxd 3/29/05 3:40 PM Page 249 [...]... from within that class For more information about inner classes, see Book III, Chapter 7 When you code more than one class in a single source file, Java still creates a separate class file for each class Thus, when you compile the DiceGame java file, the Java compiler creates two class files, named DiceGame.class and Dice.class Removing the public keyword from a class is acceptable for relatively small... in the section “Using Initializers.” For information about static initializers, refer to Book III, Chapter 3 Declaring a Class 251 ✦ Other classes and interfaces: A class can include another class, which is then called an inner class or a nested class Classes can also contain interfaces For more information about inner classes, see Book III, Chapter 7 And for information about interfaces, refer to... parameter list the same as you code it for a method Notice also that a constructor can throw exceptions if it encounters situations it can’t recover from For more information about throwing exceptions, refer to Book II, Chapter 8 Basic constructors Probably the most common reason for coding a constructor is to provide initial values for class fields when you create the object For example, suppose you have a... to the classes defined within the DiceGame .java file If you want the Dice class to be more widely available, opt for the second solution: Place it — with the public keyword — in a separate file named Dice .java If you’re going to create an application that has several public classes, create a separate folder for the application Then, save all the class files for the application to this folder If your... the name of a Java API class No rule says you have to, but if you create a class that has the same name as a Java API class, you have to use fully qualified names (like java. util.Scanner) to tell your class and the API class with the same name apart There are literally thousands of Java API classes, so avoiding them all is pretty hard But at the least, you should avoid commonly used Java class names... which is covered in Book III, Chapter 4 So you can just conveniently ignore it for now More Uses for this As I describe in the previous section, you can use the this keyword in a constructor to call another constructor for the current class You can also use this in the body of a class constructor or method to refer to the current object — that is, the class instance for which the constructor or method... must be written in a source file that has the same name as the class, with the extension java For example, a public class named Greeter must be placed in a file named Greeter .java 252 Declaring a Class The compiler coughs up a message indicating that Dice is a public class and must be declared in a file named Dice .java This problem has two solutions The first is to remove the public keyword from the... words, you can provide more than one constructor for a class, provided each constructor has a unique signature For example, here’s another constructor for the Actor class: public Actor(String first, String last, boolean good) { firstName = first; lastName = last; goodActor = good; } This constructor lets you create an Actor object with additional information besides the actor’s name: Actor a = new... functions, and then provide overloaded methods for each alternative The term overloading is accurate, but a little unfortunate Normally, when you say something is overloaded, there’s a problem For example, I once saw a picture of a Volkswagen Jetta loaded down with 3,000 pounds of lumber (You can find the picture courtesy of Snopes.com, the Urban Legend Reference Page Web site, at www.snopes.com/photos/lumber.asp.)... direct For example, you could prompt the user for the value in the constructor Or, you could call a method in the field initializer, like this: class PrimeClass { private Scanner sc = new Scanner(System.in); public int x = getX(); private int getX() { System.out.print(“Enter the starting value for x: “); return sc.nextInt(); } } Either way, the effect is the same Here are a few other tidbits of information . 3:39 PM Page 241 The Life Cycle of an Object 242 In Java, the behavior of an object is provided by its methods. Thus, the format method of the NumberFormat class is what provides the format- ting. keyword. To initialize the class, Java allocates memory for the object and sets up a reference to the object so the Java runtime can keep track of it. Then, Java calls the class constructor,. Before an object can be created from a class, the class must be loaded. To do that, the Java runtime locates the class on disk (in a .class file) and reads it into memory. Then, Java looks for

Ngày đăng: 12/08/2014, 19:21

Xem thêm: Java All-in-One Desk Reference For Dummies phần 4 docx