Java Tutorial/Class Definition/Defining Method — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:00, 1 июня 2010

Methods

  1. Methods define actions that a class"s objects (or instances) can do.
  2. A method has a declaration part and a body.
  3. The declaration part consists of a return value, the method name, and a list of arguments.
  4. The body contains code that perform the action.
  5. The return type of a method can be a primitive, an object, or void.
  6. The return type void means that the method returns nothing.
  7. 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;
  }
  
}