Home
Examples
Labs
Assignment
Marks
Midterm
Final Exam
Resources

Classes, Methods & Programs

  • a class with a main method is a program, or a Main Application Class.
  • a main application class can only have one main method.
  • program execution starts and stops in the main method.
  • all program execution does not have to take place in the main method - the main method can ask other objects, classes, or methods to help.
  • it is good programming practise to divide up the work that your program needs to do - we do this by defining new methods and classes.


Make Your Program an Object

The first step toward writing a program that divides up the work that needs to be done, is to make the program into a proper object.  We do this by defining a constructor for the main application class.  Basically, you need to move the code that used to be in the main method into a constructor method.  Next, use the constructor to create an instance of the program inside of the main method.  For example, our simple HelloWorld program should look like this now :
            class HelloWorld { 
             // Java Program - prints a hello message.
             // Note that now we are using a constructor, and the 
             // code in the main method just creates a new program
             // object.

                public HelloWorld () {
                      System.out.println("Hello World!");
                  } // end constructor

                 public static void main (String[] Args) {
                      HelloWorld hwProgram = new HelloWorld();
                  } // end main 

            } // end class HelloWorld 


Constructor Methods

A constructor is a method that creates a new object.  A constructor method always has the EXACT same name as the class that it belongs to.  In the example above, the constructor method was used in the main method to create an instance of the HelloWorld application.