Overview


As you might expect, the purpose of a constructor is to construct an object.

If the constructor has bugs, our object users will be blocked (prevented) from even using our class.

Simple Example


Say we have this Rectangle class with the two instance variables shown.
public class Rectangle {

	private int width;
	private int height;
Here is an example constructor method. Two parameters are passed in to the method and we set the instance variables with those values.
public Rectangle(int aWidth, int aHeight) {
	//Constructing a Rectangle: aWidth by aHeight
	this.width = aWidth;
	this.height = aHeight;
}


Using A Constructor


In the previous chapter it took multiple lines to construct an object and initialize it (left). With a constructor we can do it in one line (right).
Rectangle rec;
rec = new Rectangle();
rec.setWidth(11);
rec.setHeight(5);
Rectangle rec;
rec = new Rectangle(11, 5);