Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Main method and constructor

Status
Not open for further replies.

dbrb2

Instructor
Jul 19, 2004
121
GB
Sorry for the basic question I'm asking - I'm a bit unfamiliar with Java!

I'm getting a bit confused concerning the distinction between the main method and the constructor. Is the difference that the constructor is only called when the class is first created, while the main method is called each time the java application is run ...?

Thanks,

Ben
 
That's kind of it. The main method for a class is the entry point into the application - not every class needs one - only the class which you launch the app with at the command line.

The constructor for a class is called when each new instance of a class is created in the calling code. If you don't need to do anything in the constructor, you don't need to provide one - Java will create a default one for you, so you can still instantiate the class.

Hope this helps.

Mark [openup]
 
Wheras if you have a main class at all, you would only ever have one of them?

Thanks to both of you for your help



Ben
 
Actually, you can put a static main method in every class if you want -- you just need to tell the compiler which one to use.

One use for this is in unit testing -- you can put unit tests in each class' main method, and just call them one at a time. A better solution would be to use JUnit, of course, but I've seen both techniques used.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top