Notes on Java

The following examples are taken from Winston and Narasimhan, On to Java.

Class (Static) Methods

When declaring a static method,
  1. The keyword static is used in the declaration.
  2. All arguments of the function are declared in the signature.
public class Movie {
  public int script, acting, directing;

  public static int rating (Movie m) {
    return m.script + m.acting + m.directing; } }

In calling the static method,

  1. The full method name (prefixed by the class name except for calls within the same class) is used in the call.
  2. All arguments of the function are specified in the call.
  Movie m = new Movie(...);
  int r = Movie.rating(m);

Instance Methods

When declaring an instance method,
  1. No keyword static is used.
  2. The argument for the object itself is omitted.
  3. The object itself can be referred to as this, or can be used implicitly.
public class Movie {
  public int script, acting, directing;

  public int rating () {
    return script + acting + directing; } }

In calling the instance method,

  1. The variable must point to an actual object (i.e., not be null) called the target instance.
  2. The target instance is specified first, followed by a dot and the method name, then parens and any other arguments.
  Movie m = new Movie(...);
  int r = m.rating();

Note that the two methods are doing exactly the same thing, but the syntax used to specify and use the methods is different.