The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Classes and Methods

Pulling together all the code fragments from the previous section, the whole class definition looks like this:

class NewLine {

  public static void newLine () {
    System.out.println ("");
  }

  public static void threeLine () {
    newLine ();  newLine ();  newLine ();
  }

  public static void main (String[] args) {
    System.out.println ("First line.");
    threeLine ();
    System.out.println ("Second line.");
  }
}

The first line indicates that this is the class definition for a new class called NewLine. A class is a collection of related methods. In this case, the class named NewLine contains three methods, named newLine, threeLine, and main.

The other class we've seen is the Math class. It contains methods named sqrt, sin, and many others. When we invoke a mathematical function, we have to specify the name of the class (Math) and the name of the function. That's why the syntax is slightly different for built-in methods and the methods that we write:

    Math.pow (2.0, 10.0);
    newLine ();

The first statement invokes the pow method in the Math class (which raises the first argument to the power of the second argument). The second statement invokes the newLine method, which Java assumes (correctly) is in the NewLine class, which is what we are writing.

If you try to invoke a method from the wrong class, the compiler will generate an error. For example, if you type:

    pow (2.0, 10.0);

The compiler will say something like, "Can't find a method named pow in class NewLine." If you have seen this message, you might have wondered why it was looking for pow in your class definition. Now you know.



Last Update: 2011-01-24