Java Reference
In-Depth Information
public class GenericClass
{
int i;
Field with a declaration of an integer
data variable .
public int get () {
return i;
A method to obtain the value of the i
variable .
}
public void set (int j)
i = j;
A method to set the value of the i
variable. Parameter defines type for
value passed .
}
public int triple (int j) {
double f = 3.0;
i = f*j;
return i;
A method with a local double variable f. This
local variable is valid only within the
method. It must be assigned a value before
it is used .
}
}
Methods inside a class can access and modify the data in the class fields. Omitting
afew aspects that we discuss later, the structure of a method is:
access modifier return type method name (list of parameters )
{
statements, including local variable declarations
}
where:
access modifier - determines what other classes and subclasses can invoke this
method. The access modifier may be omitted, in which case the default access rules
apply. We discuss access modifiers in Chapter 5.
return type -what primitive or class type value will return from the invocation of
the method. In the above get() method, for example, the return type is int . The return
type may not be omitted. If there is no value returned, use void for the return type as
in the set() method above.
method name - follows the same identifier rules as for data names. Customarily, a
method name begins with a lowercase letter.
list of method parameters - the parameters passed to the method. Listed with
type and name as in the set (int j) method in the code above.
local variables - data variables can be declared and used within the method. Local
variables must be assigned a value before they are used. The variables are discarded
when the process returns from the method.
statements - the code to carry out the task for the particular method.
 
Search WWH ::




Custom Search