Java Driver Program?

后端 未结 1 766
梦毁少年i
梦毁少年i 2021-01-14 08:00

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

相关标签:
1条回答
  • 2021-01-14 08:55

    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.

    0 讨论(0)
提交回复
热议问题