Next page | Contents page |

this, this () & more about constructors

Within any instance code (ie, not in static methods) the keyword this is a reference to the current object. It can be used to make things clearer and occasionally it is necessary to use it, to avoid ambiguity.

Recall that we recently wrote a constructor like this:

	public Circle (double aRadius)
	{
		radius = aRadius;
	} // Circle

radius is a field, aRadius is a parameter. I deliberately gave them different names to make clear which was which. In fact that is not necessary, the compiler would understand the same meaning if it was like this:

	public Circle (double radius)
	{
		this.radius = radius;
	} // Circle

That is an example of using this to avoid ambiguity.

You could use this. in front of every use of a field or method of the current class. Some people do, but it is a bit excessive.

Constructors

We have already said that there can be several constructors in a class, with different parameters (overloaded, like methods). From within one such constructor you can call another one by writing this () (with appropriate parameters) BUT you MUST make that call the first line of the calling constructor, because the beginning of any constructor is where the object really gets created on the heap. You might well do this if there is a common chunk of code that is needed in several constructors.

We have also seen an example, in CentredCircle, where a constructor starts by calling super (), (one of) the constructor(s) of the superclass. That call must also be the first line of the subclass constructor.

You do not have to write any constructor. If there is nothing to do apart from create the object then there is no need for a constructor. The compiler will invent a default (no parameters) constructor, public MyClass () {} so you can call it by writing new MyClass (). You could also write a subclass of MyClass and call super ().

Beware that if you do not call either this () or super () at the start of a constructor, the compiler will always call super () (with no parameters) anyway, and that may not be what you want.

How can the compiler call super () if you are not extending another class? It certainly can, as the next page reveals.

Next page | Contents page |