One advantage of using additional classes, is if you've written some methods for use in one program that you think may be useful in another. By writing these methods in a separate public class (in a separate file) any program may make use of them in exactly the same way as usual just by adding the name of the class containing the method, to the beginning of the method name, i.e.
ClassName.methodName(argument);
Here's a short example, based on the printSquare example from
section 6, page .
The following code should be in a file called `MainClass.java'.
/** * Demonstrate the use of the printSquare method in ExtraClass. */ public class MainClass { public static void main (String[] args) { double x = 3.0; ExtraClass.printSquare(x); // call to print the square of x } }
The above code uses the method printSquare which is in this file, `ExtraClass.java'.
/** * Utility class with some general methods * which can be used by other classes */ public class ExtraClass { // method to print square of a value to screen public static void printSquare(double y) { System.out.println(y*y); return; } }
Both these files can be downloaded from the course web page.
Splitting code up like this means that any other program you write may also make use of the method printSquare without you needing to retype it. Obviously if you are going to do this, it pays to make your code as general as possible and to comment it as fully as possible, to avoid problems if you end up re-using it some time after it was originally written.
When compiling the file containing the main method, the compiler will automatically detect if any other files/classes are used by the program and compile these too if necessary.
Splitting up programs over several files also makes it easier for more than one person to work on a project at the same time -- useful if you are programming in a team. One person can be busy writing a main method, and as long as he/she knows what the class, method names and their arguments are, they can make use of them in the main method. Another programmer can worry about the details of how to perform the necessary calculations etc. within these additional methods.
You've probably noticed by now that the form of the call to a method of another class looks quite familiar. This is because you have been using it already, e.g. System.out.println() and the mathematical functions such as Math.sin(x). These classes and their methods are a standard part of the language and are automatically available for you to call in any Java program.