Why have a constructor and main method in same class

main() method is the entry point for any program in java. This is the method which is invoked by the JVM to execute the program.

Every class including abstract classes has a constructor. Even if you don't declare one explicitly, compiler will add a default constructor. The main() method has to belong to some public class (which will always have a constructor). Yes generally it is preferable to design another class which has all the programming logic and just instantiate this class in the main class i.e. the one with main() method in it.

But you can also have a class with main method which creates object of its own class (because you cannot access instance members from static methods).


Method public static void main(String[] args) does not create instance of your class. But constructor does.

Having main(String[]) method in several classes help to test functionality of a particular class in a big application.

Tags:

Java