Thursday, June 01, 2006

Constructor chaining

Constructors can be “chained” together, allowing one constructor to invoke another and so on until an “ultimate constructor” executes. To chain constructors, you use the this keyword to represent the constructor invocation.

Example of Constructor chaining:

public class ColoredLightBulb2
{
private boolean lit;
private String color;

public ColoredLightBulb2()
{
this(“white”);
}
public ColoredLightBulb2(String color)
{
this.color = color;
}


Two rules for Constructor chaining:

First, if you do invoke another constructor in this fashion, that invocation must come on the first line of your constructor.
The second rule of constructor chaining is that you can explicitly call only one constructor from within another constructor. It is illegal to call another constructor more than once. You could expand the first rule to say that you can invoke another constructor only on the first line and never again in the same constructor body.

0 Comments:

Post a Comment

<< Home