|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Once you've created an object, you probably want to use it for something. You may need information from it, want to change its state, or have it perform some action.Objects give you two ways to do these things:
- Manipulate or inspect its variables.
- Call its methods.
The following is the general form of a qualified name, which is also known as a long name:You may use a simple name for an instance variable when the instance variable is in scope- that is, within code for the object's class. Code that is outside the object's class must use a qualified name. For example, the code in theobjectReference.variableNameCreateObjectDemoclass is outside the code for theRectangleclass. So to refer to theorigin,width, andheightvariables within theRectangleobject namedrect_one, theCreateObjectDemoclass must use the namesrect_one.origin,rect_one.width, andrect_one.height, respectively. The program uses two of these names to display the width and the height ofrect_one:Attempting to use the simple namesSystem.out.println("Width of rect_one: " + rect_one.width); System.out.println("Height of rect_one: " + rect_one.height);widthandheightfrom the code in theCreateObjectDemoclass doesn't make sense-those variables exist only within an object-and results in a compiler error.Later, the program uses similar code to display information about
rect_two. Objects of the same type have their own copy of the same instance variables. Thus, eachRectangleobject has variables namedorigin,width, andheight. When you access an instance variable through an object reference, you reference that particular object's variable. The two objectsrect_oneandrect_twoin theCreateObjectDemoprogram have differentorigin,width, andheightvariables.The first part of the variable's qualified name,
objectReference, must be a reference to an object. You can use the name of a reference variable here, as in the previous examples, or you can 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 new object's variables:This statement creates a newint height = new Rectangle().height;Rectangleobject and immediately gets its height. In essence, the statement calculates the default height of aRectangle. Note that after this statement has been executed, the program no longer has a reference to the createdRectangle, because the program never stored the reference in a variable. The object is unreferenced, and its resources can be recycled by the Java platform.
The direct manipulation of an object's variables by other objects and classes is discouraged because it's possible to set the variables to values that don't make sense. For example, consider theRectangleclass from the previous section. Using that class, you can create a rectangle whose width and height are negative, which, for some applications, doesn't make sense.Ideally, instead of allowing direct manipulation of variables, a class would provide methods through which other objects can inspect or change variables. These methods ensure that the values of the variables make sense for objects of that type. Thus, the
Rectangleclass would provide methods calledsetWidth,setHeight,getWidth, andgetHeightfor setting and getting the width and the height. The methods for setting the variables would report an error if the caller tried to set the width or the height to a negative number. The other advantage of using methods instead of direct variable access is that the class can change the type and the names of the variables it uses for storing the width and the height without affecting its clients.However, in practical situations, it sometimes makes sense to allow direct access to an object's variables. For example, both the
Pointclass and theRectangleclass allow free access to their member variables by declaring thempublic. This keeps these classes small and simple. Also, it keeps them generally useful. Some applications might allow rectangles with negative widths and heights.The Java programming language provides an access control mechanism whereby classes can determine what other classes can have direct access to its variables. A class should protect variables against direct manipulation by other objects if those manipulations could result in values that don't make sense for objects of that type. Changes to these variables should be controlled by method calls. If a class grants access to its variables, you can assume that you can inspect and change those variables without adverse effects. To learn more about the access control mechanism, refer to Controlling Access to Members of a Class
. Also, by making the variables accessible, they become part of the class's API, which means that the writer of the class should not change their names or their types.
You also use qualified names to call an object's method. To form the qualified name of a method, you append the method name to an object reference, with an intervening period (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.TheobjectReference.methodName(argumentList); or objectReference.methodName();Rectangleclass has two methods:areato compute the rectangle's area andmoveto change the rectangle's origin. Here's theCreateObjectDemocode that calls these two methods:The first statement callsSystem.out.println("Area of rect_one: " + rect_one.area()); ... rect_two.move(40, 72);rect_one'sareamethod and displays the results. The second line movesrect_twobecause themovemethod assigns new values to the object'sorigin.xandorigin.y.As with instance variables,
objectReferencemust be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. Thenewoperator returns an object reference, so you can use the value returned fromnewto call a new object's methods:The expressionnew Rectangle(100, 50).area()new Rectangle(100, 50)returns an object reference that refers to aRectangleobject. As shown, you can use the dot notation to call the newRectangle'sareamethod to compute the area of the new rectangle.Some methods, such as
area, return a value. For methods that return a value, you can use the method call in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned byareato a variable:Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object thatint areaOfRectangle = new Rectangle(100, 50).area();areais invoked on is the rectangle returned by the constructor.A Word about Method Access
The methods in ourPointandRectangleclasses are all declaredpublic, so they are accessible to any other class. Sometimes, a class needs to restrict access to its methods. For example, a class might have a method that only subclasses are allowed to call. A class can use the same mechanism to control access to its methods as it uses to control access to its variables. To learn more about the access control mechanism, refer to Controlling Access to Members of a Class.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2004 Sun Microsystems, Inc. All rights reserved.