Start New Discussion within our Software Development Community

How do you write a driver class? i've never used one before and its sort of dropped into the spec of this program. It uses public static void main(String[] args){} right? i have 4 other classes, so what should i do?

A Driver class is nothing special. It's just a name, and it means the class in which we call all our methods. The class with the main method that we call in order to run the application.

class Methods {
  public static int add(int a, int b) {
    return a+b;
  }
  public static int sub(int a, int b) {
    return a-b;
  }
}

class MainDriver {
  public static void main(String [] args) {
      // read from the keyboard or the arguments 2 numbers:
     int a = 5;
     int b = 6;
     int c = Methods.add(a, b);
     System.out.println(c);

     int d = Methods.sub(a, b);
     System.out.println(d);
  }
}

Try to avoid declaring methods in the driver class. Just have the main and call whatever you need in the main in order to run your application.
That will include initializing objects and calling their methods:

class Person {
  public String name = "";
  public int age = "";

   public Person() {

  } 

  public Person(String n, int a) {
   name = n;
    age = a;
  }
}

class MainDriver {
  public static void main(String [] args) {
      Person p1 = new Person();
    p1.age = 12;
   p1.name = "Name 1"

   Person p2 = new Person("Name 2", 10);

System.out.println(......);
System.out.println(......);
  }
}

You have your Person class and in order to test it, you created a "driver" class with a main method.

This question has already been answered. Start a new discussion instead.