A Java program consists of one or more classes one of them must be public and must have a method with the following signature:
public static void main (String[] args)
Basically, the main()
method will instantiate appropriate objects and send them "messages" (by calling their methods) to perform the desired tasks. The main()
method should not contain any complicated program logic nor program flow control.
In the example shown below, PizzaClient
is the main class with the main()
method.
![]() |
Example:
public class PizzaClient { /** * Prints the answer to the problem stated in the above.. */ public void run() { Pizza round = new Pizza (3.99, new Circle (2.5)); Pizza rect = new Pizza (4.99, new Rectangle (6, 4)); PizzaDeal pd = new PizzaDeal(); System.out.println(round + " is a better deal than " + rect + ": " + pd.betterDeal(round, rect)); } /** * Main entry to the program to find the better deal. * Instantiates an instance of PizzaClient and tells it to run. * This is what all main() should do: instantiates a bunch of objects and * "turn them loose"! * There should be no complicated logic and/or control in main(). * @param nu not used */ public static void main (String[] nu) { new PizzaClient().run(); } } public class Rectangle implements IShape { private double _width; private double _height; /** * Initializes this Rectangle width a given width and a given height * @param w width of this Rectangle, >= 0. * @param h height of this Rectangle, >= 0. */ public Rectangle(double w, double h) { _height = h; _width = w; } /** * @returns this Rectangle's area. */ public double getArea() { return _height * _width; } /** * Overrides the inherited method from class Object. * @returns a String describing a Rectangle with its width and height. */ public String toString() { return "Rectangle(h = " + _height + ", w = " + _width + ")"; } }
Notes on the
toString()
method:
toString()
is a method that is inherited all the way from the base class, Object. It is the method that the Java system calls by default whenever a string representation of the class is needed. For instance, "This is "+ myObject
is equivalent to "This is " + myObject.toString()
. DrJava will call an object's toString()
method if you type the object's name in the interaction window, without terminating the line with a semicolon. The return value of toString()
is what prints out on the next line.