Methods
Methods are written inside a class. Methods hold a block of instructions to carry out
some task. Methods have an optional accessor (public, protected, private), a return type
(void, int, double, String, etc.), an identifier (name), parenthesis and an optional
parameter list (list of variables to receive values from the caller), a left brace to indicate
the start of the code block, the code, and the end of the code block. All computer instructions
must be wrapped up inside a method. All methods must be defined inside a class (between the
left brace ( { ) and the right brace ( } ).
Accessor return type identifier (name)
( optional parameter list )
{ // begin marker
// computer instructions (code, commands, statements)
} // end marker
Examples:
// The following MyPoint class holds the coordinates
// for a point on a 2D plane.
public class MyPoint {
// instance variables
// storage is always available
// for the life of an object of this type
int x;
int y;
// constructor MyPoint with 2 parameters
// this.x refers to the instance variable x
// this.y refers to the instance variable x
// x and y refer to the temporary parameter variables x and y
// which only exist when the constructor is called (invoked)
public MyPoint(int x, int y)
{
this.x = x;
this.y = y;
}
// method getX() will return an int
// which is the value of the instance variable x
// we do not need to say this.x because there is no local variable x
// this is called a getter method since it returns the value of an instance variable
public int getX()
{
return x; // or we could say return this.x;
}
// method setX(int x) does not return a value
// it receives a value and then assigns that value to the instance variable x
// this is called a setter method since it sets the value of an instance variable
public void setX(int x)
{
this.x = x;
}
// other methods not shown
}