Last modified: January 07, 2024
Once you have written and compiled a class, you need a main method to serve as the starting point for running your program.
When you run a Java program, Java always looks for a main method to begin execution. In BlueJ you will explicitly call the main method to run your program, but in most other Java development environments, you will simply run the class containing the main method and it will only work if the main method is declared exactly as shown below.
In this course, you are encouraged to put your main method in a separate file called a "driver" which drives the overall program logic. This allows you to potentially use each of your other classes in different programs because the class definitions are independent of the programs that use them. Here is a skeleton driver class with a main method:
public class Driver {
public static void main(String[] args) {
... code goes here
}
}
Don't worry about understanding everything yet. Here's all you need at this point:
Here's a driver for our Person class. It creates two Person objects and uses the methods we created.
public class Driver {
public static void main(String[] args) {
// Declare a Person object named joe
Person joe;
// Instantiate (create) the Person object using
// the default constructor
joe = new Person();
// Tell joe to do things
joe.printInfo();
joe.increaseAge(5);
joe.printInfo();
// Declare and initialize a Person object named bob in one line
// using a parameterized constructor
Person bob = new Person(18, 1.72, true, "Bob");
// Tell bob to do things
String answer = bob.getName();
System.out.println( "Hi, I'm " + answer );
System.out.println( "My height in inches is " + bob.heightToInches() );
}
}
Things to notice:
Person joe;
joe = new Person();
joe.printInfo();
joe.increaseAge(5);
String answer = bob.getName();