Skip to content
UoL CS Notes

Constructors

COMP122 Lectures

We recall that classes are templates for creating objects and we can instantiate an object by using the keyword new.

Behind the scenes the following happen:

  • The JVM allocates memory to store the new object.
  • A constructor method is called to initialise it.

Constructor Methods

A constructor method is a special method that gets called when the object is created. It is intended to set up the object for later use.

The syntax for constructor methods is almost the same as for normal methods, except that:

  • It must be named just like the class.
  • It has no declared return type.

Example

public class Rectangle {
	private int side;
	private String colour;
	
	public Rectangle(int s, String c) { // constructor method
		side = s;
		colour = c;
	}
}

Can be instantiated by:

Rectangle r = new Rectangle(5, "red");

Multiple Constructors

A class can have more than one constructor (which requires the to have different signatures).

This can be useful to make an object that can change one attribute without dealing with the rest.

If you don;t define any constructors, the class will automatically get a trivial default constructor without arguments.

One Constructor can Call Another

public class Rectangle {
	private int side;
	private String colour;
	
	public Rectangle(int s, String c) { // line 5
		side = s;
		colour = c;
	}
	public Rectangle(int s) {
		this(s, "blue"); // call line 5
	}
}

This can set a default of blue an just set the side length.