Notes on Java
The following examples are taken from Winston and Narasimhan,
On to Java.
Class (Static) Methods
When declaring a static method,
- The keyword static is used in the declaration.
- 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,
- The full method name (prefixed by the class name except for calls
within the same class) is used in the call.
- 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,
- No keyword static is used.
- The argument for the object itself is omitted.
- 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,
- The variable must point to an actual object (i.e., not be
null) called the target instance.
- 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.