Archive for August, 2007

Disney web site - Chapter 8 Object-Based Programming 437 public class Elevator

Friday, August 17th, 2007

Chapter 8 Object-Based Programming 437 public class Elevator { // class attributes private boolean moving; private boolean summoned; private int currentFloor = 1; private int destinationFloor = 2; private int capacity = 1; private int travelTime = 5; // class objects private ElevatorDoor elevatorDoor; private ElevatorButton elevatorButton; private Bell bell; // class constructor public Elevator() {} // class methods public void ride() {} public void requestElevator() {} public void enterElevator() {} public void exitElevator() {} public void departElevator() {} } This concludes the basics of forward engineering. We return to this example at the ends of Thinking About Objects Section 9.23 and Section 10.22 to incorporate inheritance, interfaces and event handling. SUMMARY OOP encapsulates data (attributes) and methods (behaviors) into objects; the data and methods of an object are intimately tied together. Objects have the property of information hiding. Objects might know how to communicate with one another across well-defined interfaces, but they normally are not allowed to know how other objects are implemented. Java programmers concentrate on creating their own user-defined types called classes. The non-static data components of a class are called instance variables. The static data components of a class are called class variables. Java uses inheritance to create new classes from existing class definitions. Every class in Java is a subclass of Object. Thus, every new class definition has the attributes (data) and behaviors (methods) of class Object. Keywords publicand private are member access modifiers. Instance variables and methods declared with member access modifier public are accessible wherever the program has a reference to an object of the class in which they are defined. Instance variables and methods declared with member access modifier private are accessible only to methods of the class in which they are defined. Instance variables are normally declared private and methods are normally declared public. The public methods (or public services) of a class are used by clients of the class to manipulate the data stored in objects of the class. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Ftp web hosting - 436 Object-Based Programming Chapter 8 public class Elevator

Thursday, August 16th, 2007

436 Object-Based Programming Chapter 8 public class Elevator { public Elevator() {} } 2. Use the attributes located in the second compartment to declare the member variables. For example, the private attributes moving, summoned, current- Floor, destinationFloor, capacity and travelTime of class Elevator yield public class Elevator { // class attributes private boolean moving; private boolean summoned; private int currentFloor = 1; private int destinationFloor = 2; private int capacity = 1; private int travelTime = 5; // class constructor public Elevator() {} } 3. Use the associations described in the class diagram to generate the references to other objects. For example, according to Fig. 3.23, Elevator contains one object each of classes ElevatorDoor, ElevatorButton and Bell. This yields public class Elevator { // class attributes private boolean moving; private boolean summoned; private int currentFloor = 1; private int destinationFloor = 2; private int capacity = 1; private int travelTime = 5; // class objects private ElevatorDoor elevatorDoor; private ElevatorButton elevatorButton; private Bell bell; // class constructor public Elevator() {} } 4. Use the operations located in the third compartment of Fig. 8.13 to declare the methods. For example, the public operations ride, requestElevator, enterElevator, exitElevator and departElevator in Elevator yield Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based Programming 435 Floor -floorNumber :

Thursday, August 16th, 2007

Chapter 8 Object-Based Programming 435 Floor -floorNumber : Integer -capacity : Integer = 1 ElevatorDoor -open : Boolean = false + openDoor( ) : void + closeDoor( ) : void ElevatorShaft Bell + ringBell( ) : void Light -lightOn : Boolean = false + turnOnLight( ) : void + turnOffLight( ) : void ElevatorModel - numberPeople : Integer = 0 ElevatorButton - pressed : Boolean = false + resetButton( ) : void + pressButton( ) : void FloorButton - pressed : Boolean = false + resetButton( ) : void + pressButton( ) : void + addPerson( ) : void FloorDoor -open : Boolean = false + openDoor( ) : void + closeDoor( ) : void Person -ID : Integer -moving : Boolean = true + doorOpened() : void Elevator -moving : Boolean = false - summoned:Boolean = false -currentFloor : Integer = 1 -destinationFloor:Integer = 2 -capacity : Integer = 1 - travelTime : Integer = 5 + ride( ) : void + requestElevator( ) : void + enterElevator( ) : void + exitElevator( ) : void + departElevator( ) : void Fig. 8.1313 Complete class diagram with visibility notations. Fig. Implementation: Forward Engineering Forward engineering is the process of transforming a design, such as that in a class diagram, into code of a specific programming language, such as Java. Now that we have discussed programming Java classes, we forward engineer the class diagram of Fig. 8.13 into the Java code for our elevator simulator. The generated code will represent only the skeleton, or the structure, of the model.2 In Chapters 9 and 10, we modify the code to incorporate inheritance and interfaces, respectively. In Appendix G, Appendix H and Appendix I, we present the complete, working Java code for our model. As an example, we forward engineer class Elevator from Fig. 8.13. We use this figure to determine the attributes and operations of that class. We use the class diagram of Fig. 3.23 to determine associations (and aggregations) among classes. We adhere to the following four guidelines: 1. Use the name located in the first compartment to declare the class as a public class with an empty constructor. For example, class Elevatoryields 2. So far, we have presented only about half of the case-study material we have not yet discussed inheritance, event handling, multithreading and animation. The standard development process recommends finishing the design process before starting the coding process. Technically, we will not have finished designing our system until we have discussed these additional topics, so our current code implementation might seem premature. We present only a partial implementation illustrating the topics covered in Chapter 8. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Yahoo web hosting - 434 Object-Based Programming Chapter 8 The queue hides

Wednesday, August 15th, 2007

434 Object-Based Programming Chapter 8 The queue hides an internal data representation that keeps track of the items currently waiting in line, and it offers a set of operations to its clients, namely enqueue and dequeue. The clients are not concerned about implementation of the queue. Clients merely want the queue to operate as advertised. When a client enqueues a new item, the queue should accept that item and place it internally in some kind of first-in, first-out data structure. When the client wants the next item from the front of the queue, the queue should remove the item from its internal representation and should deliver the item to the outside world in FIFO order (i.e., the item that has been in the queue the longest should be the next one returned by the next dequeue operation). The queue ADT guarantees the integrity of its internal data structure. Clients must not manipulate this data structure directly. Only the queue ADT has access to its internal data (i.e., the queue ADT encapsulates its data). Clients must cause only allowable operations to be performed on the data representation; operations not provided in the ADT’s public interface are rejected by the ADT in some appropriate manner. This could mean issuing an error message, terminating execution, or simply ignoring the operation request. 8.17 (Optional Case Study) Thinking About Objects: Starting toProgram the Classes for the Elevator Simulation In the Thinking About Objects sections in Chapters 1 through 7, we introduced the fundamentals of object orientation and developed an object-oriented design for our elevator simulation. In Chapter 8, we introduced the details of programming with Java classes. We now begin implementing our object-oriented design in Java. At the end of this section, we show how to generate code in Java, working from class diagrams. This process is referred to as forward engineering.1 Visibility Before we begin implementing our design in Java, we apply member-access modifiers (see Section 8.2) to the members of our classes. In Chapter 8, we introduced the access specifiers public and private these determine the visibilities of an object s attributes and methods to other objects. Before we create class files, we consider which attributes and methods of our classes should be public and which should be private. Software Engineering Observation 8.23 Each element of a class should have private visibility unless it can be proven that the element needs public visibility. In Chapter 8, we discussed how attributes generally should be private, but what about the operations of a class its methods? These operations are invoked by clients of that class; therefore, the methods normally should be public. In the UML, publicvisibility is indicated by placing a plus sign (+) before a particular element (i.e., a method or an attribute); a minus sign (-) indicates private visibility. Figure 8.13 shows our updated class diagram with visibility notations included. 1. G. Booch, The Unified Modeling Language User Guide. Massachusetts: Addison Wesley Long- man, Inc., 1999: 16. [Once code exists, the process of going backward from the code to reproduce design documents is called reverse engineering.] Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based Programming 433 (Web site directory) machine responds in

Tuesday, August 14th, 2007

Chapter 8 Object-Based Programming 433 machine responds in some machine-dependent manner, including the possibility of quietly producing an incorrect result. Mathematical integers do not have this problem. So the notion of a computer int is really only an approximation to the notion of a real-world integer. The same is true with float. The point is that even the built-in data types provided with programming languages like Java are really only approximations or models of real-world concepts and behaviors. We have taken int for granted until this point, but now you have a new perspective to consider. Types like int, float, char and others are all examples of abstract data types. They are essentially ways of representing real-world notions to some satisfactory level of precision within a computer system. An abstract data type actually captures two notions, namely a data representation and the operations that are allowed on that data. For example, the notion of int defines addition, subtraction, multiplication, division and modulus operations in Java, but division by zero is undefined. Another example is the notion of negative integers whose operations and data representation are clear, but the operation of taking the square root of a negative integer is undefined. In Java, the programmer uses classes to implement abstract data types. Java has a small set of primitive types. ADTs extend the base programming language. Software Engineering Observation 8.22 The programmer is able to create new types through the use of the class mechanism. These new types can be designed to be used as conveniently as the built-in types. Thus, Java is an extensible language. Although the language is easy to extend with these new types, the base language itself is not changeable. New Java classes can be proprietary to an individual, to small groups, to companies, and so on. Many classes are placed in standard class libraries intended for wide distribution. This does not necessarily promote standards, although de facto standards are emerging. The full value of Java will be realized only when substantial, standardized class libraries become more widely available than they are today. In the United States, such standardization often happens through ANSI, the American National Standards Institute. Worldwide standardization often happens through ISO, the International Standards Organization. Regardless of how these libraries ultimately appear, the reader who learns Java and object-oriented programming will be ready to take advantage of the new kinds of rapid, component-oriented software development made possible with class libraries. 8.16.1 Example: Queue Abstract Data Type Each of us stands in line from time to time. A waiting line is also called a queue. We wait in line at the supermarket checkout counter, we wait in line to get gasoline, we wait in line to board a bus, we wait in line to pay a toll on the highway, and students know all too well about waiting in line during registration to get the courses they want. Computer systems use many waiting lines internally, so we write programs that simulate what queues are and do. A queue is a good example of an abstract data type. A queue offers well-understood behavior to its clients. Clients put things in a queue one at a time using an enqueue operation, and the clients get those things back one at a time on demand using a dequeue operation. Conceptually, a queue can become infinitely long. A real queue, of course, is finite. Items are returned from a queue in first-in, first-out (FIFO) order the first item inserted in the queue is the first item removed from the queue. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

432 Object-Based Programming Chapter 8 Software Engineering Observation

Monday, August 13th, 2007

432 Object-Based Programming Chapter 8 Software Engineering Observation 8.21 Any static class variables and static class methods exist and can be used even if no objects of that class have been instantiated. 8.16 Data Abstraction and Encapsulation Classes normally hide their implementation details from the clients of the classes. This is called encapsulation or information hiding. As an example of encapsulation, let us consider a data structure called a stack. Think of a stack in terms of a pile of dishes. When a dish is placed on the pile, it is always placed at the top (referred to as pushing the dish onto the stack), and when a dish is removed from the pile, it is always removed from the top (referred to as popping the dish off the stack). Stacks are known as last-in, first-out (LIFO) data structures the last item pushed (inserted) on the stack is the first item popped (removed) from the stack. The programmer can create a stack class and hide from its clients implementation of the stack. Stacks can easily be implemented with arrays and other methods (such as linked lists; see Chapter 19, Data Structures, and Chapter 20, Java Utilities Packages and Bit Manipulation ). A client of a stack class need not know how the stack is implemented. The client simply requires that when data items are placed in the stack, they will be recalled in last-in, first-out order. This concept is referred to as data abstraction, and Java classes define abstract data types (ADTs). Although users might happen to know the details of how a class is implemented, users may not write code that depends on these details. This means that a particular class (such as one that implements a stack and its operations of push and pop) can be replaced with another version without affecting the rest of the system, as long as the public services of that class does not change (i.e., every method still has the same name, return type and parameter list in the new class definition). The job of a high-level language is to create a view convenient for programmers to use. There is no single accepted standard view that is one reason why there are so many programming languages. Object-oriented programming in Java presents yet another view. Most programming languages emphasize actions. In these languages, data exists in support of the actions programs need to take. Data is less interesting than actions, anyway. Data is crude. There are only a few built-in data types, and it is difficult for programmers to create their own new data types. This view changes with Java and the object-oriented style of programming. Java elevates the importance of data. The primary activity in Java is creating new data types (i.e., classes) and expressing the interactions among objects of those data types. To move in this direction, the programming-languages community needed to formalize some notions about data. The formalization we consider is the notion of abstract data types (ADTs). ADTs receive as much attention today as structured programming did over the last two decades. ADTs do not replace structured programming. Rather, they provide an additional formalization to further improve the program development process. What is an abstract data type? Consider the built-in type int. What comes to mind is the notion of an integer in mathematics, but int on a computer is not precisely what an integer is in mathematics. In particular, computer ints are normally quite limited in size. For example, int on a 32-bit machine is limited approximately to the range 2 billion to +2 billion. If the result of a calculation falls outside this range, an error occurs and the Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Web hosting reseller - Chapter 8 Object-Based Programming 431 Employee object constructor:

Monday, August 13th, 2007

Chapter 8 Object-Based Programming 431 Employee object constructor: Susan Baker Employee object constructor: Bob Jones Employee object finalizer: Susan Baker; count = 1 Employee object finalizer: Bob Jones; count = 0 Fig. 8.21 Using a staticclass variable to maintain a count of the number of objects of a class (part 3 of 3). Eventually, the garbage collector reclaims the memory for these objects (or the memory is reclaimed by the operating system when the program terminates). Because it is not guaranteed when the garbage collector will execute, we make an explicit call to the garbage collector with line 40, which uses publicstatic method gc from class System (java.lang package) to indicate that the garbage collector immediately should make a best effort attempt to collect objects that have been marked for garbage collection. However, this is just a best effort it is possible that no objects or a subset of the garbage objects will be collected. In our example, the garbage collector did execute before lines 49 51 displayed the results of the program. The last line of the output indicates that the number of Employeeobjects in memory is 0 after the call to System.gc(). Also, the last two lines of the command window output show that the Employee object for Susan Baker was finalized before the Employee object for BobJones. Remember, the garbage collector is not guaranteed to execute when System.gc()is invoked nor is it guaranteed to collect objects in a specific order, so it is possible that the output of this program on your system may differ. [Note: A method declared staticcannot access nonstaticclass members. Unlike nonstaticmethods, a staticmethod has no thisreference because, static class variables and staticclass methods exist independent of any objects of a class and before any objects of the class have been instantiated.] Common Programming Error 8.12 Referring to the this reference in a static method is a syntax error. Common Programming Error 8.13 It is a syntax error for a static method to call an instance method or to access an instance variable. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

430 Object-Based Programming Chapter 8 6 public class (Web servers)

Sunday, August 12th, 2007

430 Object-Based Programming Chapter 8 6 public class EmployeeTest { 7 8 // test class Employee 9 public static void main( String args[] ) 10 { 11 // prove that count is 0 before creating Employees 12 String output = “Employees before instantiation: ” + 13 Employee.getCount(); 14 15 // create two Employees; count should be 2 16 Employee e1 = new Employee( “Susan”, “Baker” ); 17 Employee e2 = new Employee( “Bob”, “Jones” ); 18 19 // Prove that count is 2 after creating two Employees. 20 // Note: static methods should be called only via the 21 // class name for the class in which they are defined. 22 output += “nnEmployees after instantiation: ” + 23 “nvia e1.getCount(): ” + e1.getCount() + 24 “nvia e2.getCount(): ” + e2.getCount() + 25 “nvia Employee.getCount(): ” + Employee.getCount(); 26 27 // get names of Employees 28 output += “nnEmployee 1: ” + e1.getFirstName() + 29 ” ” + e1.getLastName() + “nEmployee 2: ” + 30 e2.getFirstName() + ” ” + e2.getLastName(); 31 32 // If there is only one reference to each employee (as 33 // on this example), the following statements mark 34 // those objects for garbage collection. Otherwise, 35 // these statement simply decrement the reference count 36 // for each object. 37 e1 = null; 38 e2 = null; 39 40 System.gc(); // suggest call to garbage collector 41 42 // Show Employee count after calling garbage collector. 43 // Count displayed may be 0, 1 or 2 depending on 44 // whether garbage collector executed immediately and 45 // number of Employee objects it collects. 46 output += “nnEmployees after System.gc(): ” + 47 Employee.getCount(); 48 49 JOptionPane.showMessageDialog( null, output, 50 “Static Members and Garbage Collection”, 51 JOptionPane.INFORMATION_MESSAGE ); 52 53 System.exit( 0 ); 54 } 55 56 } // end class EmployeeTest Fig. 8.21 Using a staticclass variable to maintain a count of the number of objects of a class (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 8 Object-Based Programming 429 (Web site template) structor and decremented

Saturday, August 11th, 2007

Chapter 8 Object-Based Programming 429 structor and decremented (line 25) by the finalizer. When no objects of class Employee exist, member countcan still be referenced, but only through a call to publicstatic method getCount(lines 43 46), as in: Employee.getCount() which determines the number of Employeeobjects currently in memory. Note that when there are no objects instantiated in the program, the Employee.getCount() method call is issued. However, when there are objects instantiated, method getCount can also be called through a reference to one of the objects, as in e1.getCount() Good Programming Practice 8.11 Always invoke static methods by using the class name and the dot operator (.). This emphasizes to other programmers reading your code that the method being called is a static method. Notice that the Employee class has a finalize method (lines 23 28). This method is included to show when it is called by the garbage collector in a program. Method finalize normally is declared protected so it is not part of the public services of a class. We will discuss the protected access modifier in detail in Chapter 9. Method main of the EmployeeTestapplication class (Fig. 8.21) instantiates two Employee objects (lines 16 17). When each Employee object s constructor is invoked, lines 12 13 of Fig. 8.20 store references to that Employee s first name and last name String objects. Note that these two statements do not make copies of the original Strings arguments. Actually, String objects in Java are immutable they cannot be modified after they are created (class String does not provide any set methods). Because a reference cannot be used to modify a String, it is safe to have many references to one Stringobject in a Java program. This is not normally the case for most other classes in Java. If Java String objects are immutable, why are we able to use the + and += operators to concatenate Strings? As we discuss in Chapter 10, Strings and Characters, the String concatenation operations actually result in the creation of new String objects containing the concatenated values. The original String objects actually are not modified. When main is done with the two Employee objects, the references e1 and e2 are set to nullat lines 37 38. At this point references e1and e2no longer refer to the objects that were instantiated on lines 16 17. This marks the objects for garbage collection because there are no more references to the objects in the program. 1 // Fig. 8.21: EmployeeTest.java 2 // Test Employee class with static class variable, 3 // static class method, and dynamic memory. 4 import javax.swing.*; Fig. 8.21 Using a staticclass variable to maintain a count of the number of objects of a class (part 1 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

428 Object-Based (Msn web hosting) Programming Chapter 8 1 // Fig.

Wednesday, August 8th, 2007

428 Object-Based Programming Chapter 8 1 // Fig. 8.20: Employee.java 2 // Employee class definition. 3 public class Employee extends Object { 4 private String firstName; 5 private String lastName; 6 private static int count; // number of objects in memory 7 8 // initialize employee, add 1 to static count and 9 // output String indicating that constructor was called 10 public Employee( String first, String last ) 11 { 12 firstName = first; 13 lastName = last; 14 15 ++count; // increment static count of employees 16 System.out.println( “Employee object constructor: ” + 17 firstName + ” ” + lastName ); 18 } 19 20 // subtract 1 from static count when garbage collector 21 // calls finalize to clean up object and output String 22 // indicating that finalize was called 23 protected void finalize() 24 { 25 –count; // decrement static count of employees 26 System.out.println( “Employee object finalizer: ” + 27 firstName + ” ” + lastName + “; count = ” + count ); 28 } 29 30 // get first name 31 public String getFirstName() 32 { 33 return firstName; 34 } 35 36 // get last name 37 public String getLastName() 38 { 39 return lastName; 40 } 41 42 // static method to get static count value 43 public static int getCount() 44 { 45 return count; 46 } 47 48 } // end class Employee Fig. 8.20 Employeeclass that uses a staticclass variable to maintain a count of the number of Employeeobjects in memory. When objects of class Employee exist, member count can be used in any method of an Employee object in this example, count is incremented (line 15) by the con Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01