We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Trying to learn what is OOP and write some class. And I have a question - what is "constructor"? My class is working without constructor, so why do we need it?
Answers
A constructor is a function that runs when an new instance of the class is created. It's job is to create the new object. It allows you to have all the logic that creates the object in one place.
Let's say you have a class that draws an ellipse. Without a constructor, you have the width, height and location of the ellipse defined in the class. No matter how many objects you instantiate from that class, they will look exactly the same. And they will appear at the same place. (Without the use of random or noise or something like that)
But you want to fill the screen with ellipses in many different sizes. So you add a constructor. In the constructor you pass through location, width and height. That way each object is unique.
You don't need a constructor if you don't want/need varieties in your objects.
Compare this:
To this:
And this:
In the first chunk of code, the logic to generate the random variables for a Dot object is duplicated in two places - not good! You want to make sure your code is DRY - Don't Repeat Yourself.
In the second chunk of code, this has been fixed - the random variables for a Dot object are now being done in the constructor. More importantly, the Dot class is now "in charge" of creating and setting up the Dot objects. This is good OOP, as the object doesn't need to rely on "external" logic to set the object up.
Drawing the objects is still done "externally" in the second chunk of code. This is fixed in the third chunk. Now the Dot class has total control over how the Dot objects are setup and drawn.
Make sense?
This class tutorial got 1 example of a class called Bicycle which doesn't have any constructors.
Therefore an empty 1 is created behind the scenes for us: $-)
http://docs.Oracle.com/javase/tutorial/java/concepts/class.html
A more complete explanation about constructors below: :-B
http://docs.Oracle.com/javase/tutorial/java/javaOO/constructors.html
And an excerpt about "no constructors" case from that tutorial link: :P
Oh, wow, so many answers! Thanks, people!