go to previous page   go to home page   go to next page

Answer:

No. You need only one main() method for the Java virtual machine to use in starting your program.


A Tiny Example

class HelloObject
{
  // method definition
  public void speak()
  {
    System.out.println("Hello from an object!");
  }
}

public class HelloTester
{
  public static void main ( String[] args )
  {
    HelloObject anObject = new HelloObject();
    
    anObject.speak();
  }
}
reference to an object

Above is a complete program which includes two class definitions. The definition of class HelloObject includes a method but no instance variables, so objects of class HelloObject have no instance variables. The class does have a constructor but it is not explicitly defined in the code (this will be discussed further).

Class HelloTester contains only the static main() method.

When the main() method starts, it constructs a HelloObject and then invokes that object's speak() method.

The variable anObject is a reference variable that points to the newly created object.

If you are compiling and running Java from the command line, both classes can be put into one file. The name of the file must match the name of the class that contains the main() method, so this file must be named HelloObject.java. The class that contains main() must use the public modifier. For now, don't use any modifiers for the other classes. Upper and lower case are important both in the file name and in the class name.

If you are using an Integrated Development Environment (IDE) like BlueJ, you may need to use separate files for each class. With BlueJ you don't need a class to contain main(). You can run the HelloObject directly from the IDE. You may need to experiment with your environment.

Here is an example run where both classes are in one file:

C:\JavaCode>javac HelloTester.java
C:\JavaCode>java HelloTester
Hello from an object!
C:\JavaCode>

QUESTION 7:


go to previous page   go to home page   go to next page