Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a constructor and main method in same class

Tags:

java

Why would you ever need to have a constructor in your class that contains public static void main (String[] args){}?

Why not have a separate class with the constructor instead and instantiate it?

like image 641
Bob Avatar asked Apr 13 '13 10:04

Bob


People also ask

Do constructors need to be called in the main method?

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation. The this keyword in Java is a reference to the object of the current class. Using it, you can refer a field, method or, constructor of a class.

What can be the purpose of having multiple constructors in the same class?

A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.

Can you call a constructor in a method in the same class?

Constructor chaining can be done in two ways: Within same class: It can be done using this() keyword for constructors in the same class. From base class: by using super() keyword to call the constructor from the base class.

Can main class have constructor in Java?

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.


1 Answers

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).

like image 171
Ankur Shanbhag Avatar answered Sep 20 '22 05:09

Ankur Shanbhag