Java Reference
In-Depth Information
After this sequence executes,
car2
refers to the same object as
car3
. The object referred to
by
car1
is unchanged.
Methods
As explained, instance variables and methods are constituents of classes. So far, the
Vehicle
class contains data, but no methods. Although data-only classes are perfectly valid, most
classes will have methods. Methods are subroutines that manipulate the data defined by the
class and, in many cases, provide access to that data. In most cases, other parts of your pro-
gram will interact with a class through its methods.
A method contains one or more statements. In well-written Java code, each method per-
forms only one task. Each method has a name, and it is this name that is used to call the
method. In general, you can give a method whatever name you please. However, remember
that
main( )
is reserved for the method that begins execution of your program. Also, don't
use Java's keywords for method names.
When denoting methods in text, this topic has used and will continue to use a convention
that has become common when writing about Java. A method will have parentheses after
its name. For example, if a method's name is
getval
, it will be written
getval( )
when its
name is used in a sentence. This notation will help you distinguish variable names from
method names in this topic.
The general form of a method is shown here:
Here,
ret-type
specifies the type of data returned by the method. This can be any valid type,
including class types that you create. If the method does not return a value, its return type
must be
void
. The name of the method is specified by
name
. This can be any legal identifi-
er other than those already used by other items within the current scope. The
parameter-list
is a sequence of type and identifier pairs separated by commas. Parameters are essentially
variables that receive the value of the
arguments
passed to the method when it is called. If
the method has no parameters, the parameter list will be empty.