Java Driver Program?

2020-03-26 06:29发布

问题:

I'm really confused about java classes and driver programs. What is the syntax of the code for a driver program and what should and should not be inside it? For the driver program we need perhaps to have a main program inside it but what about the java class , don't we need to have any ...? Do i need to have this for both the java class and the driver program or only in the driver:

public static void main(String[] args) { }

回答1:

As referenced from here:

What is a driver class? (Java)

A "Driver class" is often just the class that contains a main. In a real project, you may often have numerous "Driver classes" for testing and whatnot, or you can build a main into any of your objects and select the runnable class through your IDE, or by simply specifying "java classname."

Example:

This is not a driver class since it doesn't contain any main method. In this case, it has the method "hello":

public class HelloWorld {
  public void hello() {
    System.out.println("Hello, world!");
  }
}

versus this one - which is a driver class since it contains a main method, and is the class that runs HelloWorld:

public class HelloWorldDriver {
  public static void main(String[] args) {
    HelloWorld sayhello = new HelloWorld();
    sayhello.hello();
  }
}

Hence the name "driver class" - as the class HelloWorldDriver "drives" or rather, controls the instantiation and usage of the class HelloWorld.



标签: java driver