Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Mini-Lab: Constructing Objects Mini-Lab: Creating Fish in an Aquarium Reading Specifications and Writing Client Code This set of Mini-Lab Exercises is the first in a series in which students build a small program with several fish moving around in an aquarium. The set includes the following exercises: Getting Started Populating the Aquarium     (Concepts: Declaring, constructing, and initializing variables; providing meaningful names; reading class documentation; passing parameters) Seeing is Believing     (Concepts: Reading class documentation for method information; invoking methods) Let's Move!     (More practice reading class documentation for method information and invoking methods) Each section contains an Introduction to a problem or task, descriptions or examples of one or more Concepts to apply in solving the problem or completing the task, and an Exercise. Before working through this Mini-Lab, students should understand the role of the main method in an application, the role of classes and objects, and the syntax for documenting code with comments. Getting Started Introduction The Aquarium Simulation program is meant to simulate several fish moving in an aquarium. A skeleton of the program already exists. The main class, the one that runs the simulation, is the AquaSimApplication class. There is also an Aquarium class and an AquaFish class. The skeleton program constructs an Aquarium object in the main method; in the exercises that follow, you will be creating several AquaFish objects in the aquarium and directing them to move. The program also contains an AquaSimGUI class that provides the graphical user interface for the Aquarium Lab Series. The interface is an area where the program can display a graphical picture of an aquarium and its fish. The program also includes a utility class called NavigationalAide that helps a fish keep track of its position and move around in the aquarium. You will need to read class documentation for these classes, but you will not need to read or modify their code as part of this lab series. Exercise: Downloading and Running the Initial Program You can download the files needed for the Aquarium Lab Series separately from the list below or download them as a BlueJ package. You will also be able to download the lab series instructions as a zip file once all of the labs have been updated.   The code for the Aquarium simulation program consists of five classes and a graphics library: AquaSimApplication (class with trivial main method, which merely constructs an empty aquarium) Aquarium class (representing an aquarium) AquaFish class (representing fish in the aquarium) NavigationalAide class (a supplement or aide to the AquaFish class, which keeps track of a fish's size, location, and direction; separated out from the AquaFish class to make that class easier to read) AquaSimGUI class (provides the user interface, e.g., buttons, text output, and graphical display) jpt.jar (a graphics library from Northeastern University ) All classes are covered by the GNU General Public License. As a quick way to become familiar with what the Aquarium simulation program does, compile and run the program (remember that the main method is in the AquaSimApplication class. You should see a window appear with a Start button. This is the program's graphical user interface. Some instructions should appear either at the bottom of this window or in a separate window. When you press the Start button, you should just see a blue background representing the aquarium. That is all the program does for now. Close the graphical user interface window to quit the program. Exercise: A Simple Modification Edit the AquaSimApplication class and modify the first output statement to welcome users to the fish aquarium program rather than state that it will be an aquarium simulation. Test the modified program. Does it behave any differently? Why, or why not? (How you compile the program will depend on the Java development environment you use.) Populating the Aquarium Introduction The main method in AquaSimApplication.java creates an aquarium, but it doesn't have any fish in it. To add fish to the aquarium, we must declare variables for the fish, construct the actual fish objects (AquaFish instances), and initialize the new variables to be references to the newly constructed fish. The AquaFish class documentation gives the specifics on how to construct objects of the class. Concepts: Declare-Construct-Initialize, Passing Parameters To create a variable that will refer to an object in Java, you need to construct the variable (which is initially just a potential reference to an object) and then set it to refer to the object. Constructing the variable is also called declaring the variable because you are declaring, or specifying, its type; setting its value is called initializing it. Until you initialize the variable, it is a reference to a null (non-existant) object. MyClass newObject;                   // creates null reference Give the variable a meaningful name to make your code easier to read, understand, and maintain. The variable can be assigned to refer to an existing object, or to a newly constructed object. A newly constructed object is initialized by a constructor method, which, in Java, always has the same name as the class. It is often possible to pass parameters to a constructor to help with the initialization. A constructor that does not require any parameters is called a default constructor. For any given class, read the class documentation to determine how to construct and initialize objects of that class. newObject = oldObject;    // initializes new reference to existing object newObject = new MyClass();            // initializes ref. to new object constructed using default constructor newObject = new MyClass(initValue);   // initializes ref. to object constructed using one-parameter constructor To prevent the creation of null references, the two steps of creating and initializing a variable are often done in a single statement. MyClass newObject = oldObject;        // creates new reference to existing object MyClass newObject = new MyClass();            // creates ref. to object constructed using default constructor MyClass newObject = new MyClass(initValue);   // creates ref. to object constructed using one-parameter constructor Example: Constructing an Aquarium Let's look at an example from the Aquarium class. In this class, there is a single constructor. How do we know? There is only one "method" in the Constructor Summary section of the class documentation. Also, a constructor always has the same name as the class, and there is only one "method" called Aquarium in the class documentation. public Aquarium(int width, int height) Constructs an Aquarium with user-specified size. Parameters: width - width of the aquarium when displayed (in pixels) height - height of the aquarium when displayed (in pixels) This specification tells us that the constructor is public, so code in other classes may use it, and that it requires two integer parameters. When we construct an Aquarium object we need to provide two integer values for the two parameters, although we do not need to restate that they are integer values. Thus, we could construct a 600 x 400 aquarium as follows: Aquarium myAquarium = new Aquarium(600, 400); Constructor Basics: Every constructor has the same name as the class of objects it constructs. A class can have more than one constructor. Since they all have the same name, you can tell them apart by the number of parameters (each has a different numer of parameters). To construct a new object, use the new keyword and the constructor name. Always put parentheses after the constructor name. If the constructor requires parameters, provide values of the appropriate types in the parentheses (the values can be constants, variables, or even expression results). The order of multiple parameters must match the order in the specification. Exercise: Constructing Objects Read the initial version of the main method in AquaSimApplication.java. This method has three sections. The first constructs the objects needed to run the simulation. The second and third sections, which are currently much shorter, run the simulation (or will, when we have added some more functionality to it) and wrap up the program, reminding the user how to quit. Research the class documentation of (or specification for) the AquaFish class to discover how to construct a fish. Notice that there are two AquaFish constructors, so two different ways to construct a fish. For this lab, just concentrate on the simpler, one-parameter constructor. Edit the main method in AquaSimApplication.java to declare and construct three fish variables at the end of the first section. Give your new variables names that convey their purpose. Using blank lines, separate this sequence of new statements, which together perform a single function, from the existing code around them. Add a single comment preceding them that describes the purpose of the sequence. Before you test your modified program, decide whether you expect this modification to change the appearance of the display or not, and, if so, how you expect it to be different. Then test the program. Was the actual result what you expected or not? If not, did you have the wrong expectation, or is the behavior of the program wrong? Hint: look at the comment above the statement that tells the user interface to show the aquarium. This exercise directed you to construct three fish, but have they been added to the aquarium yet? Seeing is Believing Introduction We have constructed new fish, but we cannot see them because we have not yet added them to the aquarium. How do we know what operations we can use to do this and how to use them? Concepts: Reading Class Documentation ... A method specification in the class documentation for a class will tell you whether the method is accessible to you whether you need to provide any information to the method in the form of parameters if so, how many parameters to provide the order of the parameters and the type of each parameter whether the method will return a value to the calling method (and so can be used in larger expressions) if so, the type of the return value Let's look at two examples from the Aquarium class: width and validLoc. public int width() Determines the width of the aquarium. Returns: the width of the aquarium public boolean validLoc(int xCoord, int yCoord) Determines whether the given coordinates specify a valid location (one that exists within the bounds of the aquarium). Parameters: xCoord - x coordinate of location to be checked yCoord - y coordinate of location to be checked Returns: true if the specified location is within the bounds of the aquarium What can we learn from these declarations? Both methods are associated with the Aquarium class, so they are operations on Aquarium objects. In other words, we will want to invoke them on objects of the Aquarium class, as in myAquarium.methodCall(). Both methods are public, so code in other classes may use them. Both have return values (width returns an integer value; validLoc returns a boolean value), so we should capture the value returned in a variable or embed the method call in a larger expression. The width method does not take any parameters and returns an int. The validLoc method requires two parameters and returns a boolean value. Thus, this method may be used in a logical expression. ... and Invoking Methods How can we use this knowledge? First, remember that a method is an operation tied to a particular object, so you have to specify which object should perform the operation as well as what operation you want the object to do. You may also need to provide extra information, in the form of parameters. Just as, when playing ball, you might yell, "Hey, Pat! Catch the ball!", in code you might write pat.catch(ball); // Tell the object "pat" to catch the object "ball" Using the Aquarium example from above, if myAquarium is an instance of the Aquarium class and x and y are well-defined integer values, then the following are valid examples of these two methods. int aquariumWidth = myAquarium.width(); // call method with no parameters; save result in variable if ( myAquarium.validLoc(x, y) ) // call method with parameters; use return value to decide whether to do something else     // do something with the valid location ... As with constructors, you do not need to specify the type of the parameters as you pass them; just make sure the parameters are of the right type. Nor do you specify the return type of a method as you call it. A method with a void return type does not return any value to the method that called it. Instead, it usually modifies its object, produces output, or changes the state of the program in some other way. Like other methods, it may or may not require parameters. The changeDir (change direction) method in the AquaFish class is an example of a void method. public void changeDir() Reverses direction. Since changeDir does not return anything, it cannot be embedded in an expression or an assignment statement. A void method is a statement on its own. For example, aFish.changeDir(); Method Basics: A class may have many methods, with many names. A class may have several methods with the same name, but each must have a different number or type of parameters to tell them apart. Use the imperative subject-verb style to invoke a method on a particular object: object.method(); Always put parentheses after the method name when invoking the method. If the method requires parameters, provide values of the appropriate types in the parentheses (the values can be constants, variables, or even expression results). The order of multiple parameters must match the order in the specification. Exercise Research the class documentation for the Aquarium class to discover how to add a fish to an aquarium. Modify the main method in the AquaSimApplication class to add all three of your new fish to the aquarium. (Analysis Question: where should this code go in the main method?) Again, before you test your modified program, decide whether you expect this modification to change the appearance of the display or not, and, if so, how you expect it to be different. Then test the program. Was the actual result what you expected or not? If not, did you have the wrong expectation, or is the behavior of the program wrong? Let's Move! We can finally see our newly constructed fish in the aquarium, but the program isn't very interesting because the fish aren't doing anything. We need to read the class documentation for the AquaFish class to learn how to get our fish to do something interesting (like move). Exercise Now it is time to start running the aquarium simulation. Research the class documentation for the AquaFish class to discover how to make a fish move forward. Add statements to the main method to move your three fish one step forward. (Where should these statements be added?) After you make the fish move, redisplay the aquarium. (Do you need to read the class documentation for the AquaSimGUI class to know how to do that, or do you have an example in the main method already?) Make sure there are blank lines that separate this sequence of new statements, which together perform a single function, from the existing code around them. Make sure that the internal comments reflect the behavior of your code. Test your modified program. Was the behavior as you expected or not? If not, did you have the wrong expectation, or is the behavior of the program wrong? You may occasionally only see two fish (or even one!). This can happen when a larger fish overlaps and hides a smaller fish. Run your program a number of times to verify that you usually see three fish. Update the class documentation at the top of the file to reflect your modifications.