|
|
Objects, Classes, and Interfaces |
Once you've created an object, you'll probably want to use it for something. Suppose, for example, that after creating a newRectangleobject, you would like to move it to a different location. Say, the rectangle is an object in a drawing program and the user just clicked the mouse over the rectangle and dragged it to a new location.The
Rectangleclass provides two equivalent ways to move the rectangle:Option 2 is often considered "more object-oriented" and safer because you manipulate the object's variables indirectly through its protective layer of methods rather than twiddling directly with them. Manipulating an object's variables directly is often considered error-prone; you could potentially put the object into an inconsistent state. However, a class would not (and should not) make its variables available for direct manipulation by other objects if it were possible for those manipulations to put the object in an inconsistent state. Java provides a mechanism whereby classes can restrict or allow access to its variables and methods by objects of another type. This section discusses calling methods and manipulating variables that have been made accessible to other classes. To learn more about controlling access to members refer to Controlling Access to Members of a Class.
- Manipulate the object's
x,yvariables directly.- Call the
movemethod.
Rectangle'sxandyare accessible to other classes, so we can assume that manipulating aRectangle'sxandyvariables directly is safe.Referencing an Object's Variables
First, let's focus on how to inspect and modify the Rectangle's position by modifying itsxandyvariables directly. The next section will show you how to move the rectangle by calling itsmovemethod.To access an object's variables, simply append the variable name to an object reference with an intervening '.' (period).
Suppose you have a rectangle namedobjectReference.variablerectin your program. You can access itsxandyvariables withrect.xandrect.y, respectively. Now that you have a name forrect's variables, you can use those names in Java statements and expressions as though they were the names of "regular" variables. Thus to move the rectangle a new location you would write:Therect.x = 15; // change x position rect.y = 37; // change y positionRectangleclass has two other variables--widthandheight--that are accessible to objects outside theRectangle. You can use the same notation to access them:rect.widthandrect.height. So you could calculate the rectangle's area using this statement:When you access a variable through an object, you are referencing that particular object's variables. Ifarea = rect.height * rect.width;bobis also a rectangle with a different height and width thanrect, then the following instruction, which calculates the area of the rectangle namedbob, will give a different result than the previous instruction, which calculates the area of the rectangle namedrect:area = bob.height * bob.width;Note that the first part of the name of an object's variables (the
objectReferenceinobjectReference.variable) must be a reference to an object. While you can use a variable name here, you can also use any expression that returns an object reference. Recall that thenewoperator returns a reference to an object. So you could use the value returned fromnewto access a brand new object's variables:height = new Rectangle().height;Calling an Object's Methods
Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '.' (period), and provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, just use empty parentheses.Let's see what this means in terms of moving the rectangle. To moveobjectReference.methodName(argumentList); or objectReference.methodName();rectto a new location using itsmovemethod write the following Java statement:This Java statement callsrect.move(15, 37);rect'smovemethod with two integer parameters, 15 and 37. This statement has the effect of moving therectobject by modifying itsxandyvariables and is equivalent to the assignment statments used previously:If you want to move a different rectangle, the one namedrect.x = 15; rect.y = 37;bob, to a new location you would write:As you see from these examples, method calls are directed at a specific object; the object specified in the method call is the object that responds to the instruction. Method calls are also known as messages. Like real-world messages, object messages must be addressed to a particular recipient. You get different results depending on which object is the recipient of the message. In the example above, when you send the object namedbob.move(244, 47);rectamovemessage,rectmoves to the new location. When you send the object namedbobamovemessage,bobmoves. Very different results. To understand messages more fully, please see the page What Are Messages?A method call is an expression (see Expressions
for more information) and evaluates to some value. The value of a method call is its return value, if it has one. You will often wish to assign the return value of a method to a variable or use the method call within the scope of another expression or statement. The
movemethod doesn't return a value (it's declaredvoid). However,Rectangle'sinsidemethod does. Theinsidemethod takes an x, y coordinate and returnstrueif that point lies within the rectangle. So you could use theinsidemethod to do something special if some point, say the current mouse location, were inside the rectangle:Remember that the method call is a message to the named object. In this case, the object named is theif (rect.inside(mouse.x, mouse.y)) { . . . // mouse is in the rectangle . . . } else { . . . // mouse is outside of the rectangle . . . }Rectanglenamedrect. Askingrectif the mouse cursor location represented bymouse.xandmouse.yis in it is a message torect--the named object:You will likely get a different response if you send the same message torect.inside(mouse.x, mouse.y)bob.As stated previously, the
objectReferencein the method callobjectReference.method()must be an object reference. While you can use a variable name here, you can also use any expression that returns an object reference. Recall that thenewoperator returns a reference to an object. So you could use the value returned fromnewto call a brand new object's methods:The expressionnew Rectangle(0, 0, 100, 50).equals(anotherRect)new Rectangle(0, 0, 100, 50)evaluates to an object reference that refers to aRectangleobject. So, as you can see, you can use the dot notation to call the new rectangle'sequalsmethod to determine if the new rectangle is equal to the one specified inequals's argument list.
|
|
Objects, Classes, and Interfaces |