Java Tutorial/Class Definition/Defining Method
Methods
- Methods define actions that a class"s objects (or instances) can do.
- A method has a declaration part and a body.
- The declaration part consists of a return value, the method name, and a list of arguments.
- The body contains code that perform the action.
- The return type of a method can be a primitive, an object, or void.
- The return type void means that the method returns nothing.
- The declaration part of a method is also called the signature of the method.
For example, here is the getSalary method that returns a double.
public class MainClass {
double getSalary() {
return 0.0;
}
}
Passing Objects to a Method
class Sphere {
double radius; // Radius of a sphere
Sphere() {
}
// Class constructor
Sphere(double theRadius) {
radius = theRadius; // Set the radius
}
}
public class MainClass {
public static void main(String[] arg){
Sphere sp = new Sphere();
aMethod(sp);
}
private static void aMethod(Sphere sp){
System.out.println(sp);
}
}
Returning From a Method
public class MainClass {
private int aField;
public void aMethod() {
}
public double volume() {
return 50;
}
}