This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
i am very new to java programming and basically trying to teach myself off of a book. i am struggeling to cearly understand what constructors are? what exactly do they do? how to define them? and perhaps any other information that may help to underatnd them better.
Constructors are very similar to methods, although they are not considered as methods in the Java Language Specification. You declare them very much like you declare a method. The main differences are that a constructor must have the same name as the class it is in and has no return type. The purpose of a constructor is to initialize variables and other state for a new object that is created.
I know this explanation will seem a little hazy, but that is mostly because it is still very acedemic in nature. I suggest that you write a class with a constructor to get a better understand how they work. If you are in a course at school, perhaps the current homework assignment will be a good place to start. There are plenty of examples on the web that you mgiht want to work from as well.
Once you get started writing your own class, please come back with some more questions. The more specific your quetions are the better.
A constructor is responsible for creating an object of the class type it belongs to.
In Java it's really easy to do this. Here's a really easy example:
That's it! It's not real exciting of course; this code doesn't "do" anything, except show you want a constructor looks like. It has the same name as the class (and the name is case-sensitive). It looks like a method in the sense that it supports a parameter section and a code section. Both of those are empty in this example, as you can see.
So let's look at a slightly more interesting example:
In this example there's some code in the constructors. Although there are two constructors now, they're distinct to the compiler because their parameter lists are different.
This simple example shows the primary purpose of a compiler; to initialize some, all or no elements of the object at creation time. The println() calls I put in aren't in the best place, by the way, but I wanted to show you something easy that you could play with right now.
Make visible what, without you, might perhaps never have been seen. - Robert Bresson