Java Reference
In-Depth Information
ch = obj.calc (25, count, "Hello");
char calc ( int numl, int num2, String message)
{
int sum = numl + num2;
char result = message.charAt (sum);
return result;
}
FIGURE 4.8
Passing parameters from the method invocation to the declaration
local data as opposed to instance data.
Recall that instance data is declared in a class but not inside any particular method.
Local data has scope limited to only the method in which it is
declared. The variable result declared in the toString method
of the Die class is local data. Any reference to result in any other
method of the Die class would have caused the compiler to issue an
error message. A local variable simply does not exist outside of the
method in which it is declared. On the other hand, instance data, declared at the
class level, has a scope of the entire class; any method of the class can refer to it.
Because local data and instance data operate at different levels of scope, it's
possible to declare a local variable inside a method with the same name as an
instance variable declared at the class level. Referring to that name in the method
will reference the local version of the variable. This naming practice obviously has
the potential to confuse anyone reading the code, so it should be avoided.
The formal parameter names in a method header serve as local data for that
method. They don't exist until the method is called, and they cease to exist when
the method is exited. For example, the formal parameter value in the setFaceValue
method comes into existence when the method is called and goes out of existence
when the method finishes executing.
can be declared inside a method, making it
KEY CONCEPT
A variable declared in a method is
local to that method and cannot be
used outside of it.
Bank Account Example
Let's look at another example of a class and its use. The Transactions class
shown in Listing 4.3 contains a main method that creates a few Account objects
and invokes their services.
 
Search WWH ::




Custom Search