4.7 Better use of the void main Method |
If you look at the declartion of the void main method you will see that it is a static method and it therefore has the limitations of the static method. Since the void main method is the entry point to the application these limitations nedd to be avoided.
The solution is simple, but looks a little odd. What you do is in the void main method of the class you create an instance of the class and then calls it's methods. For example:
public class SayClass { protected int messageCounter = 0; // declare integer set to 0 public void sayMessage(String aMessage) // method that prints message to console { // message includes a counter. messageCounter = messageCounter + 1; System.out.println("No " + messageCounter + ": " + aMessage); } public static void main(String[] args) // void main { SayClass sayer = new SayClass(); // creates an instance of the SayClass called sayer sayer.sayMessage("The first message !"); // displays the first message sayer.sayMessage("Yet another message."); // displays the second message } }