Methods
Objective #1: Use methods.
- Methods are reusable sections of code that perform actions
on or with an object. For example, the Rectangle class
has a translate method.
The translate method allows a programmer
to move the Rectangle object's x and y properties.
If you implemented a Tank class, you might
include move or shoot methods
while properties of the Tank class might
include x and y locations
as well as an ammo property.
- It is proper style to begin the name of a method and the name of a property
with a lowercase letter as in width or move. It is proper style to capitalize
the name of the class itself as in Rectangle or Tank.
- The public interface of a class is simply
the list of constructors and methods that can be used to create and manipulate
objects from the class in a program developed by a client programmer.
Think
of the
Java
API as being a set of class interfaces.
- According to the principles of object-oriented design
and programming, an object has state and behavior. Its behavior is
defined by the methods that are included in its class definition. Its state is
defined by the properties that are included in its class definition.
- To implement an individual method within a class means
to type code into body of the method so the method knows how to perform when
it is called. The method name, parameters, and body statements together are
called the method's definition.
- It is possible to include two methods with the same
name in a class. For example, you can have one method in a Tank class
named move that
accepts no parameters and another method named move that
accepts one parameter as in the following example. These two methods are
called overloaded methods since they share the same name
but have different parameter lists (also known as method signatures). One
parameter list can be different from another by having a different number
of parameters,
having
parameters
with
different data types, or by having the same number of parameters
but with
the data
types in a different order. So the following methods could both be used in a Tank class even though they have the same name. Since they have different parameter lists, they are treated as two different methods.
public void move()
{
myX = myX + 5;
}
public void move(int amount)
{
myX = myX + amount;
}
The following methods are considered to have the same parameter list (i.e. method signature) even though they have different return types. Therefore it would cause an error to attempt to have both these methods in a class.
public void move(int amount, int start)
{
myX = start + amount;
}
public int move(int amount, int start)
{
return myX + amount + start;
}
Objective #2: Call methods.
- Within a client program, you must declare an object variable
from a class and type the method name that you are calling after the name of
that
object variable as in
public static void main(String[] args)
{
Fish nemo = new Fish(10, 20);
Fish willie = new Fish(30, 15);
System.out.println("My horizontal position is " + getX());
}
Here the method call getX() is
not legal since the compiler
doesn't know which
fish (nemo or willie)
you are talking about.
- Within a class, you may call another method within the same
class without having to type anything in front of the dot operator. Although,
you may optionally use the keyword this.
public void moveRight()
{
myX = getX() + 10;
}
or
public void moveRight()
{
myX = this.getX() + 10;
}
Here is another example of calling a method from within another method:
public void moveBackAndForth()
{
moveRight();
moveLeft();
}
public void moveRight()
{
myX = myX + 5;
}
public void moveLeft()
{
myX = myX - 5;
}
Notice again that you do not need an object variable name in front of the name of the method that you are calling. In other words, it does not make sense to type tankA.moveRight(); since there is no object variable named tankA in the Tank class itself. An object variable named tankA would likely only exist in a separate client program.
Objective #3: Pass parameters to methods.
- One or more parameters may be passed to a method.
The identifiers x and y in the following move method
are explicit parameters. More specifically, they are sometimes called formal
parameters as
well since their names are simply formal placeholders that only store values
passed to them.
public void move(int x, int y)
{
myX = myX + x;
myY = myY + y;
}
A value or variable identifier that is found in the call statement that calls
a
method from a client program such as the values 20 & 30 in the following statement
is called
an actual
parameter (and sometimes called an argument).
tankA.move(20, 30);
- A whole object variable may even be passed as a parameter!
The following method
public void move(Tank another)
{
myX = another.getX();
myY = another.getY();
}
could be called with the call statement
tankA.move(tankB);
where tankB is an actual parameter, another is
an explicit formal parameter and
tankA is the implicit parameter.
- View this great tutorial on how to write a class: http://nhsweb.calvertnet.k12.md.us/Stroh/JAVA/FlashTut
Objective #4: Use local variables within methods.
- Local variables can be declared and used
within individual methods in a class as in this move method from our example Tank class:
public void shoot()
{
int num = 0;
num = myAmmo - 1;
myAmmo = num;
}
Clearly though the use of the local variable num is a waste in this example
since the single statement myAmmo--; would
have sufficed.
Local variables are similar to variables
in programming languages like Visual Basic. A local variable can store a numeric
variable. Technically there is no string primitive data type in Java. More
about that later. An int variable
can store whole numbers while a double variable
can store floating-point values (i.e. decimal numbers). A boolean variable
can store either true or false. We will learn more about variables and data
types in the next chapter. In addition to int and double local variables, you
can also declare and instantiate an object as a local variable though this
will rarely need to be done for most of our programming exercises in this course.
But here is an example anyway:
public void shoot()
{
Tank tankTemp = new Tank();
tankTemp.move(30, 50);
myX = tankTemp.myX;
myY = tankTemp.myY;
}
The object variable tankTemp is local to the method shoot. Furthermore, it is
legal to use an object in the implementation of one of its own methods! It is
also legal to reference tankTemp's private myX property since this code is found
within the class itself. However, using an accessor as in myX
= tankTemp.getX(); is legal as well.
- A local variable MUST be initialized when it is declared inside of a method.
For example, the method
public void reload(int amount)
{
int sum;
sum = amount + myAmmo;
myAmmo = sum;
}
will cause a compile error since sum was not
initialized. Unlike Visual Basic, Java does not automatically initialize local
variables to zero.
- A local variable only has a scope of the method in
which it is declared. That is, you cannot refer to a local variable in another
method. Once the method
has executed and when the compiler reaches the method's closing curly brace,
all of the method's local variables are discarded and "garbage collected". Garbage collection is an aspect of Java in which the memory occupied by unused
variables is constantly being reclaimed as a program executes.
- To access a local variable within the method where it is
declared, you simply refer to the name of the local variable. You do not attach
the local variable name to an object variable name. For example, the statement
System.out.println(num);
correctly accesses the local variable num (assuming
that num is declared in the method where this
statement appears).
- Be careful not create a side effect when writing an accessor method. One type of side effect is a logic error that modifies a property of a class in addition to returning
a property's value.
- Constants are declared by placing
the keyword final before
the usual declaration. For example, you
might use the statement
final int PI =
3.1415926;
which declares a constant named PI that
can be used over and over again
without fear of accidentally changing the value of PI to
something else. A constant is also useful
since the name DOZEN is much easier to recognize
and reuse than typing out the number 3.1415926. Constants should be named
with all-capital letters for good style and underscores should be used to
separate multiple words as in SPEED_OF_LIGHT
Within a class such as the Tank class, a constant would be declared near
the properties of the class with the statement
private final static int MAX_AMMO = 25;
In this example, the constant is made private so that MAX_AMMO can only be
used within the Tank class. However, it is sometimes useful to use public rather than private so that the constant can be used in client programs,
test classes, and other classes. The static keyword is used so that there
is only one copy of MAX_AMMO rather than one copy per Tank object that happens
to be instantiated at a given moment. We will study more about this use of static later.
Objective #5: Be able to use static methods
- A method can be typed out in a class that is static. Static methods are also called class methods.
- A method is a static method if the keyword static is used in the method's header. Here is an example of a static method
public static void displayAreaFormula()
{
System.out.println("area of rectangle = length * width");
}
- You call a static by typing the name of the class followed by the dot operator and the name of the method. You do not call a static method with the name of a specific object variable.
- Example
public class Rectangle
{
// properties, constructors, accessors, & modifiers
public static void displayAreaFormula()
{
System.out.println("area of rectangle = length * width");
}
}
public class RectangleTest
{
public static void main(String[] args)
{
Rectangle.displayAreaFormula();
}
}
An error would occur if you replaced the main method with this code....
Rectangle box = new Rectangle();
box.displayAreaFormula();