Section 11.6. Creating a Main Method


[Page 366 (continued)]

11.6. Creating a Main Method

Up to now we have created objects and tried out new methods in the interactions pane. However, there is a special method called a main method that you can use to create objects and invoke methods. A main method must have the following method declaration:

public static void main(String[] args)


The method must be a public static method called main and must take an array of String objects as a parameter. It doesn't matter if you call the array of strings args or some other name. The convention is just to use the name args. It must be a public method so that it can be called by objects of other classes. It must be static because no objects of the class exist when you start execution of the method. The first thing you usually do in a main method is create one or more objects of the class and then invoke a method or methods on the created objects.


[Page 367]

Here is a main method that you can use to create some students:

public static void main (String[] args)   {     Student student1 = new Student("Barb Ericson");     System.out.println(student1);     double[] gradeArray1 = {90,88,95,96,93};     Student student2 = new Student("Mark Guzdial",gradeArray1);     System.out.println(student2);   }


In DrJava you can execute the main method of the current class by clicking on TOOLS and then RUN DOCUMENT'S MAIN METHOD. It will show output in the interactions pane and in the console pane.

> java Student Student object named: Barb Ericson Average: 0.0 Student object named: Mark Guzdial Average: 92.4


If you are using the command-line tools from Sun you can invoke a main method on a class using:

java ClassName


As you may have noticed, this is what DrJava does when you ask it to run the document's main method.



Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net