Quick Index
Problem Statement


For this example we're going extend our previous work on Rectangle.

We'll first extend our Rectangle model class:

ConstructorDescription
Add a "no-arg constructor"Set both ivars to zero
Add a constructor with one method parameterSet both ivars to the one method parameter
Add a constructor with two method parametersSet the "width" and "height" ivars to the first and second method parameters respectively


Then we'll extend our RectangleTests class to test the new model methods. We'll add these three test methods:


Getting Started


Copy both "Rectangle.java" and "RectangleTests.java" (from our previous work referenced above) into
a new working directory.

No-Arg Constructor


Here is a no-arg constructor.

We set both ivars to zero.
	public Rectangle() {
		//Constructing a Rectangle: 0 by 0
		this.width = 0;
		this.height = 0;
	}

Constructor With One Parameter


Here is a constructor with one method parameter.

We set both ivars to the parameter that is passed in. In other words this constructor instantiates a square.

"Instantiate" is another word you'll see in object coding that means "construct"
	public Rectangle(int aDimension) {
		//Constructing a Square: aDimension by aDimension
		//A square is  special type of rectangle
		this.width = aDimension;
		this.height = aDimension;
	}

Constructor With Two Parameters


Here is a constructor with two parameters.

We set the "width" and "height" ivars to the first and second method parameters respectively.
	public Rectangle(int aWidth, int aHeight) {
		//Constructing a Rectangle: aWidth by aHeight
		this.width = aWidth;
		this.height = aHeight;
	}

Using The Constructors


Here are some examples of different ways we can use the constructors.

We'll see this first-hand in the tests that follow.
Rectangle rec1, rec2, rec3, square1, square2;
rec1 = new Rectangle(11, 5);
rec2 = new Rectangle(1000, 500);
rec3 = new Rectangle();  //Using no-args constructor
square1 = new Rectangle(800);
square2 = new Rectangle(1);

Test Code


The latest example Rectangle and RectangleTests code can be downloaded here...

	public void testNoArgConstructor()  {

		Rectangle rec;
		rec = new Rectangle();
		System.out.println("\n-- testNoArgConstructor --");
		System.out.println("Expected: 0 x 0");
		System.out.println("Actual: " + rec.toString());
	}

	public void testConstructorWithOneParam()  {

		//Constructing a square
		//Which is a Rectangle with both sides equal
		Rectangle square;
		square = new Rectangle(8);
		System.out.println("\n-- testConstructorWithOneParam --");
		System.out.println("Expected: 8 x 8");
		System.out.println("Actual: " + square.toString());
	}

	public void testConstructorWithTwoParams()  {
		Rectangle rec;
		rec = new Rectangle(10, 5);
		System.out.println("\n-- testConstructorWithTwoParams --");
		System.out.println("Expected: 10 x 5");
		System.out.println("Actual: " + rec.toString());
	}


Try-It and Video 💡


👉🏼 Try It

📹 Video