Archive for December, 2007

Web hosting e commerce - 298 Methods Chapter 6 Each variable identifier

Monday, December 31st, 2007

298 Methods Chapter 6 Each variable identifier has the attributes duration (lifetime) and scope. An identifier s duration determines when that identifier exists in memory. An identifier s scope is where the identifier can be referenced in a program. Identifiers that represent local variables in a method have automatic duration. Automatic-duration variables are created when program control reaches their declaration; they exist while the block in which they are declared is active; and they are destroyed when the block in which they are declared is exited. Java also has identifiers of static duration. Variables and references of static duration exist from the point at which the class in which they are defined is loaded into memory for execution until the program terminates. The scopes for an identifier are class scope and block scope. An instance variable declared outside any method has class scope. Such an identifier is known in all methods of the class. Identifiers declared inside a block have block scope. Block scope ends at the terminating right brace (}) of the block. Local variables declared at the beginning of a method have block scope, as do method parameters, which are considered to be local variables of the method. Any block may contain variable declarations. A recursive method is a method that calls itself, either directly or indirectly. If a recursive method is called with a base case, the method returns a result. If the method is called with a more complex problem, the method divides the problem into two or more conceptual pieces: A piece that the method knows how to do and a slightly smaller version of the original problem. Because this new problem looks like the original problem, the method launches a recursive call to work on the smaller problem. For recursion to terminate, the sequence of smaller and smaller problems must converge to the base case. When the method recognizes the base case, the result is returned to the previous method call, and a sequence of returns ensues all the way up the line until the original call of the method returns the final result. Both iteration and recursion are based on a control structure: Iteration uses a repetition structure; recursion uses a selection structure. Both iteration and recursion involve repetition: Iteration explicitly uses a repetition structure; recursion achieves repetition through repeated method calls. Iteration and recursion each involve a termination test: Iteration terminates when the loop-continuation condition fails; recursion terminates when a base case is recognized. Iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges to the base case. Recursion repeatedly invokes the mechanism and, consequently the overhead, of method calls. This repetition can be expensive in terms of both processor time and memory space. The user presses the Enter key while typing in a JTextFieldto generate an action event. The event handling for this GUI component is set up like a JButton: Aclass must be defined that implements ActionListener and defines method actionPerformed. Also, the JText- Field s addActionListener method must be called to register the event. It is possible to define methods with the same name, but different parameter lists. This feature is called method overloading. When an overloaded method is called, the compiler selects the proper method by examining the arguments in the call. Overloaded methods can have different return values and must have different parameter lists. Two methods differing only by return type will result in a syntax error. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Adult web hosting - Chapter 6 Methods 297 An important feature

Sunday, December 30th, 2007

Chapter 6 Methods 297 An important feature of method definitions is the coercion of arguments. In many cases, argument values that do not correspond precisely to the parameter types in the method definition are converted to the proper type before the method is called. In some cases, these conversions can lead to compiler errors if Java s promotion rules are not followed. The promotion rules specify how types can be converted to other types without losing data. The promotion rules apply to mixed-type expressions. The type of each value in a mixed-type expression is promoted to the highest type in the expression. Method Math.random generates a double value from 0.0 up to, but not including, 1.0. Values produced by Math.random can be scaled and shifted to produce values in a range. The general equation for scaling and shifting a random number is n = a + (int) ( Math.random() * b ); where a is the shifting value (the first number in the desired range of consecutive integers) and b is the scaling factor (the width of the desired range of consecutive integers). A class can inherit existing attributes and behaviors (data and methods) from another class specified to the right of keyword extends in the class definition. In addition, a class can implement one or more interfaces. An interface specifies one or more behaviors (i.e., methods) that you must define in your class definition. The interface ActionListener specifies that a class must define a method with the first line public void actionPerformed( ActionEvent actionEvent ) The task of method actionPerformed is to process a user s interaction with a GUI component that generates an action event. This method is called in response to the user interaction (the event). This process is called event handling. The event handler is the actionPerformed method, which is called in response to the event. This style of programming is known as event-driven programming. Keyword final declares constant variables. Constant variables must be initialized before they are used in a program. Constant variables are often called named constants or read-only variables. A JLabelcontains a string of characters to be displayed on the screen. Normally, a JLabelindicates the purpose of another GUI element on the screen. JTextFields get information from the user or displays information on the screen. When the user presses a JButton, the program normally responds by performing a task. Container method setLayout defines the layout manager for the applet s user interface. Layout managers are provided to arrange GUI components on a Container for presentation purposes. FlowLayout is the simplest layout manager. GUI components are placed on a Container from left to right in the order in which they are attached to the Container with method add. When the edge of the container is reached, components are continued on the next line. Before any event can be processed, each GUI component must know which object in the program defines the event-handling method that will be called when an event occurs. Method addActionListener is used to tell a JButtonor JTextField that another object is listening for action events and defines method actionPerformed. This procedure is called registering the event handler with the GUI component. To respond to an action event, we must define a class that implements ActionListener and defines method actionPerformed. Also, we must register the event handler with the GUI component. Method showStatus displays a String in the applet container s status bar. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

296 Methods Chapter 6 For now, we do (Web server hosting)

Saturday, December 29th, 2007

296 Methods Chapter 6 For now, we do not concern ourselves with operation parameters or return types; we attempt to gain only a basic understanding of the operations of each class. As we continue our design process, the number of operations belonging to each class may vary we might find that new operations are needed or that some current operations are unnecessary and we might determine that some of our class operations need non-void return types. SUMMARY The best way to develop and maintain a large program is to divide it into several smaller modules. Modules are written in Java as classes and methods. A method is invoked by a method call. The method call mentions the method by name and provides arguments in parentheses that the called method requires to perform its task. If the method is in another class, the call must be preceded by a reference name and a dot operator. If the method is static, it must be preceded by a class name and a dot operator. Each argument of a method may be a constant, a variable or an expression. A local variable is known only in a method definition. Methods are not allowed to know the implementation details of any other method (including its local variables). The on-screen display area for a JApplethas a content pane to which the GUI components must be attached so they can be displayed at execution time. The content pane is an object of class Containerfrom the java.awt package. Method getContentPane of class JAppletreturns a reference to the applet s content pane. The general format for a method definition is return-value-type method-name( parameter-list ) { declarations and statements } The return-value-type states the type of the value returned to the calling method. If a method does not return a value, the return-value-type is void. The method-name is any valid identifier. The parameter-list is a comma-separated list containing the declarations of the variables that will be passed to the method. If a method does not receive any values, parameter-list is empty. The method body is the set of declarations and statements that constitute the method. The arguments passed to a method should match in number, type and order with the parameters in the method definition. When a program encounters a method, control transfers from the point of invocation to the called method, the method executes and control returns to the caller. A called method can return control to the caller in one of three ways. If the method does not return a value, control returns at the method-ending right brace or by executing the statement return; If the method does return a value, the statement return expression; returns the value of expression. There are three ways to call a method the method name by itself, a reference to an object followed by the dot (.) operator and the method name, and a class name followed by the dot (.) operator and a method name. The last syntax is for staticmethods of a class. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 Methods 295 (Top ten web hosting) From the ring the

Saturday, December 29th, 2007

Chapter 6 Methods 295 From the ring the elevator bell phrase listed with class Elevator, we conclude that class Bellshould have an operation that provides a service namely, ringing. We list the ringBell operation under class Bell. When arriving at a floor, the elevator signals its arrival to the doors. The elevator door responds by opening, as implied by the phrase opens [the elevator s] door associated with class Elevator. Therefore, class ElevatorDoor needs an operation that opens its door. We place the openDoor operation in the bottom compartment of this class. The phrase closes [the elevator s] door indicates that class ElevatorDoor needs an operation that closes its door, so we place the closeDoor operation in the same compartment. Class ElevatorShaftlists turns off light and turns on light in its verb-phrases column, so we create the turnOffLight and turnOnLight operations and list them under class Light. The resets floor button phrase implies that the elevator instructs a floor button to reset. Therefore, class FloorButton needs a resetButton operation. The phrase walks on floor listed by class Person is not an operation, because a person decides to walk across the floor in response to that person s creation. However, the phrases presses floor button and presses elevator button are operations pertaining to the button classes. We therefore place the pressButton operation under classes Floor- Button and ElevatorButton in our class diagram (Fig. 6.21). The phrase rides elevator implies that Elevator needs a method that allows a person to ride the elevator, so we place operation ride in the bottom compartment of Elevator. The enters elevator and exits elevator phrases listed with class Person suggest that class Elevator needs operations that correspond to these actions.1 We place operations enterElevator and exitElevator in the bottom compartment of class Elevator. The requests elevator phrase listed under class FloorButton implies that class Elevator needs a requestElevator operation. The phrase signals elevator to move to opposite floor listed with class ElevatorButton implies that Elevator- Button informs Elevator to depart. Therefore, the Elevator needs to provide a departure service; we place a departElevatoroperation in the bottom compartment of Elevator. The phrases listed with classes FloorDoor and ElevatorDoor mention that the doors by opening signal a Person object to enter or exit the elevator. Specifically, a door informs a person that the door has opened. (The person then enters or exits the elevator, accordingly.) We place the doorOpened operation in the bottom compartment for class Person. In addition, the ElevatorDoor opens and closes the FloorDoor, so we assign openDoor and closeDoor to the bottom compartment of class FloorDoor. Lastly, the creates person action associated with class ElevatorModel refers to creating a Person object and adding it to the simulation. Although we can require ElevatorModel to send a create person and an add person message, an object of class Person cannot respond to these messages, because that object does not yet exist. We discuss new objects when we consider implementation in Chapter 8. We place the operation addPerson in the bottom compartment of ElevatorModel in the class diagram of Fig. 6.21 and anticipate that the application user will invoke this operation. 1. At this point, we can only guess what these operations do. For example, perhaps these operations model real-world elevators, some of which have sensors that detect when passengers enter and exit. For now, we simply list these operations. We will discover what, if any, actions these operations perform as we continue our design process. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

294 Methods Chapter 6 To create operations, we (Yahoo free web hosting)

Friday, December 28th, 2007

294 Methods Chapter 6 To create operations, we examine the verb phrases listed with each class. The phrase moves to other floor listed with class Elevatorrefers to the activity in which the elevator moves between floors. Should moves be an operation of class Elevator? The elevator decides to move in response to a button press. A button signals the elevator to move, but a button does not actually move the elevator therefore, moves to other floor does not correspond to an operation. (We include the operations for informing the elevator to move to the other floor later in the discussion, when we discuss the verb phrases associated with the buttons.) The arrives at a floor phrase is also not an operation, because the elevator itself decides when to arrive on the floor after five seconds of travel. The resets elevator button phrase associated with class Elevator implies that the elevator informs the elevator button to reset. Therefore, class ElevatorButtonneeds an operation to provide this service to the elevator. We place this operation (resetButton) in the bottom compartment of class ElevatorButtonin our class diagram (Fig. 6.21). We represent the names of the operations as method names (by following the names with a pair of parentheses) and include the return type after the colon: resetButton() : void The parentheses can contain a comma-separated list of the parameters that the operation takes in this case, none. For the moment, most of our operations have no parameters and a voidreturn type; this might change as our design and implementation processes proceed. Floor floorNumber : Integer capacity : Integer = 1 Person ID : Integer moving : Boolean = true doorOpened( ) : void ElevatorDoor open : Boolean = false openDoor( ) : void closeDoor( ) : 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 ElevatorShaft FloorButton pressed : Boolean = false resetButton( ) : void pressButton( ) : void Bell ElevatorModel numberOfPeople : Integer=0 ringBell( ) : void Light lightOn : Boolean = false turnOnLight( ) : void turnOffLight( ) : void ElevatorButton pressed : Boolean = false resetButton( ) : void pressButton( ) : void addPerson( ) : void FloorDoor open : Boolean = false openDoor( ) : void closeDoor( ) : void Fig. 6.2121 Classes with attributes and operations. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 Methods 293 obtains the Graphicsobject for

Thursday, December 27th, 2007

Chapter 6 Methods 293 obtains the Graphicsobject for you and invokes another method, called update. Method updateinvokes method paintand passes to it the Graphicsobject. The repaint method is discussed in detail in Chapter 18, Multimedia. 6.17 (Optional Case Study) Thinking About Objects: IdentifyinClass Operations In the Thinking About Objects sections at the ends of Chapters 3, 4 and 5, we performed the first few steps in the object-oriented design for our elevator simulator. In Chapter 3, we identified the classes we need to implement. In Chapter 4, we created a class diagram that models the structure of our system. In Chapter 5, we examined objects states and modeled objects activities and state transitions. In this section, we concentrate on determining the class operations (or behaviors) needed to implement the elevator simulator. In Chapter 7, we concentrate on the collaborations (interactions) between objects of our classes. An operation of a class is a service that the class provides to clients (users) of that class. Consider the operations of some real-world classes. A radio s operations include setting its station and volume (typically invoked by a person adjusting the radio s controls). A car s operations include accelerating (invoked by the driver pressing the accelerator pedal), decelerating (invoked by the driver pressing the brake pedal and/or releasing the gas pedal), turning and shifting gears. We can derive many of the operations of each class directly from the problem statement. To do so, we examine the verbs and verb phrases in the problem statement. We then relate each of these to particular classes in our system (Fig. 6.20). Many of the verb phrases in Fig. 6.20 help us determine the operations of our classes. Class Verb phrases Elevator moves to other floor, arrives at a floor, resets elevator button, rings elevator bell, signals its arrival, opens its door, closes its door ElevatorShaft turns off light, turns on light, resets floor button Person walks on floor, presses floor button, presses elevator button, rides elevator, enters elevator, exits elevator Floor [none in the problem statement] FloorButton requests elevator ElevatorButton closes elevator door, signals elevator to move to opposite floor FloorDoor signals person to enter elevator (by opening) ElevatorDoor signals person to exit elevator (by opening), opens floor door, closes floor door Bell [none in the problem statement] Light [none in the problem statement] ElevatorModel creates person Fig. 6.2020 Verb phrases for each class in simulator. Fig. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

292 Methods Chapter 6 Method When the method (Web server extensions)

Thursday, December 27th, 2007

292 Methods Chapter 6 Method When the method is called and its purpose public void init() This method is called once by the appletvieweror browser when an applet is loaded for execution. It performs initialization of an applet. Typical actions performed here are initialization of instance variables and GUI components of the applet, loading of sounds to play or images to display (see Chapter 18, Multimedia) and creation of threads (see Chapter 15, Multithreading). public void start() This method is called after the initmethod completes execution and every time the user of the browser returns to the HTML page on which the applet resides (after browsing another HTML page). This method performs any tasks that must be completed when the applet is loaded for the first time into the browser and that must be performed every time the HTML page on which the applet resides is revisited. Typical actions performed here include starting an animation see (Chapter 18, Multimedia) and starting other threads of execution (see Chapter 15, Multithreading). public void paint( Graphics g ) This method is called after the initmethod completes execution and the start method has started executing to draw on the applet. It is also called automatically every time the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen then uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphicsobject gthat is automatically passed to the paintmethod for you. public void stop() This method is called when the applet should stop executing normally, when the user of the browser leaves the HTML page on which the applet resides. This method performs any tasks that are required to suspend the applet s execution. Typical actions performed here are to stop execution of animations and threads. public void destroy() This method is called when the applet is being removed from memory normally, when the user of the browser exits the browsing session. This method performs any tasks that are required to destroy resources allocated to the applet. Fig. 6.18 JAppletmethods that the applet container calls during an applet s execution . Method repaint is also of interest to many applet programmers. The applet s paint method normally is called by the applet container. What if you would like to change the appearance of the applet in response to the user s interactions with the applet? In such situations, you may want to call paint directly. However, to call paint, we must pass it the Graphicsparameter it expects. This requirement poses a problem for us. We do not have a Graphicsobject at our disposal to pass to paint. (We discuss this issue in Chapter 18, Multimedia.) For this reason, class JAppletprovides method repaint. The statement repaint(); Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Chapter 6 Methods 291 8 public class MethodOverload (Web design rates)

Wednesday, December 26th, 2007

Chapter 6 Methods 291 8 public class MethodOverload extends JApplet { 9 10 // first definition of method square with double argument 11 public int square( double x ) 12 { 13 return x * x; 14 } 15 16 // second definition of method square with double argument 17 // causes syntax error 18 public double square( double y ) 19 { 20 return y * y; 21 } 22 23 } // end class MethodOverload MethodOverload.java:18: square(double) is already defined in MethodOverload public double square( double y ) ^ MethodOverload.java:13: possible loss of precision found : double required: int return x * x; ^ 2 errors Fig. 6.17Compiler error messages generated from overloaded methods with Fig. 6.17 identical parameter lists and different return types (part 2 of 2). 6.16 Methods of Class JApplet We have written many applets to this point in the text, but we have not yet discussed the key methods of class JApplet that the applet container calls during the execution of an applet. Figure 6.18 lists the key methods of class JApplet, specifies when they get called and explains the purpose of each method. These JApplet methods are defined by the Java API to do nothing unless you provide a definition in your applet s class definition. If you would like to use one of these methods in an applet you are defining, you must define the first line of each method as shown in Fig. 6.18. Otherwise, the applet container will not call your versions of the methods during the applet s execution. Defining the methods as discussed here is known as overriding the original method definition. The applet container will call the overridden version of a method for your applet before it attempts to call the default versions inherited from JApplet. Overriding is discussed in detail in Chapter 9. Common Programming Error 6.18 Providing a definition for one of the JApplet methods init, start, paint, stop or destroy that does not match the method headers shown in Figure 6.18 results in a method that will not be called automatically during execution of the applet. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

290 Methods Chapter 6 Called square with int (Fedora web server)

Tuesday, December 25th, 2007

290 Methods Chapter 6 Called square with int argument: 7 Called square with double argument: 7.5 Fig. 6.16Using overloaded methods (part 2 of 2). Fig. 6.16 Overloaded methods are distinguished by their signature a combination of the method s name and its parameter types. If the Java compiler looked only at method names during compilation, the code in Fig. 6.16 would be ambiguous the compiler would not know how to distinguish between the two square methods. Logically, the compiler uses longer mangled or decorated names that include the original method name, the types of each parameter and the exact order of the parameters to determine if the methods in a class are unique in that class. For example, in Fig. 6.16, the compiler might use the logical name square of int for the square method that specifies an int parameter and square of double for the squaremethod that specifies a doubleparameter. If a method foo s definition begins as void foo( int a, float b ) then the compiler might use the logical name foo of int and float. If the parameters are specified as void foo( float a, int b ) then the compiler might use the logical name foo of float and int. Note that the order of the parameters is important to the compiler. The preceding two foo methods are considered to be distinct by the compiler. The logical names of methods used by the compiler did not mention the return types of the methods, because methods cannot be distinguished by return type. The program in Fig. 6.17 illustrates the compiler errors generated when two methods have the same signature and different return types. Overloaded methods can have different return types, but must have different parameter lists. Also, overloaded methods need not have the same number of parameters. Common Programming Error 6.17 Creating overloaded methods with identical parameter lists and different return types is a syntax error. 1 // Fig. 6.17: MethodOverload.java 2 // Overloaded methods with identical signatures and 3 // different return types. 4 5 // Java extension packages 6 import javax.swing.JApplet; 7 Fig. 6.17Compiler error messages generated from overloaded methods with Fig. 6.17 identical parameter lists and different return types (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Web and email hosting - Chapter 6 Methods 289 1 // Fig. 6.16:

Monday, December 24th, 2007

Chapter 6 Methods 289 1 // Fig. 6.16: MethodOverload.java 2 // Using overloaded methods 3 4 // Java core packages 5 import java.awt.Container; 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class MethodOverload extends JApplet { 11 12 // set up GUI and call versions of method square 13 public void init() 14 { 15 JTextArea outputArea = new JTextArea(); 16 Container container = getContentPane(); 17 container.add( outputArea ); 18 19 outputArea.setText( 20 “The square of integer 7 is ” + square( 7 ) + 21 “nThe square of double 7.5 is ” + square( 7.5 ) ); 22 } 23 24 // square method with int argument 25 public int square( int intValue ) 26 { 27 System.out.println( 28 “Called square with int argument: ” + intValue ); 29 30 return intValue * intValue; 31 32 } // end method square with int argument 33 34 // square method with double argument 35 public double square( double doubleValue ) 36 { 37 System.out.println( 38 “Called square with double argument: ” + doubleValue ); 39 40 return doubleValue * doubleValue; 41 42 } // end method square with double argument 43 44 } // end class MethodOverload Fig. 6.16Using overloaded methods (part 1 of 2). Fig. 6.16 Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01