CONSTRUCTORS


CONTENTS

1. Default Constructors
2. Copy Constructors
 
3. Constructors within Constructors



1. DEFAULT CONSTRUCTORS

A default constructor of the form:

public Circle() {
    }

which creates an instance of the class Circle is created automatically in the absence of any user defined constructor. However, should the user define some other constructor, for example one with an argument:

public Circle(double cRad) {
    circleRadius = cRad;
    }

no "empty" (default) constructor will be created. If such an empty constructor is required this must be explicitly encoded by the programmer.




2. COPY CONSTRUCTORS

It is quite often necessary to make a copy of an instance. This should not be done as follows:

public static void main(String[] args) throws IOException {
    double radius = 2.0
    Circle circle1 = new Circle(radius);
    Circle circle2 = circle1;
    }

as this will simply create an alias (called circle2) for the instance circle1, both will be references to the same instance. (Note that the above makes use of the Circle class defined previously.

Instead we should define a copy constructor, in the Circle class, as follows:

public Circle(Circle oldCircle) {
    circleRadius =  oldCircle.circleRadius;
    }

which would be used as follows:

public static void main(String[] args) throws IOException {
    double radius = 2.0
    Circle circle1 = new Circle(radius);
    Circle circle2 = Circle(circle1);
    }



3. CONSTRUCTORS WITHIN CONSTRUCTORS

If we have constructor of the form:

public Circle(int radius) {
    circleRadius =  radius;
    }

we can rewrite the copy constructor given in the foregoing section as:

public Circle(Circle oldCircle) {
    this(oldCircle.circleRadius);
    }

The body of this constructor, this(oldCircle.circleRadius), is a call to another constructor. When the this object is used in the above manner it should be interpreted as "use the constructor of the current class that matches the arguments after the this object".

We could use a similar technique to create a constructor that assigns a default value to circleRadius:

public Circle() {
    this(2.0);
    }



Created and maintained by Frans Coenen. Last updated 04 December 2001