next up previous contents
Next: Using private class variables Up: 8 Object oriented programming Previous: Non-static methods   Contents

Constructor methods

Constructor methods are a particular type of non-static method. They are given the same name as the class and are automatically called when an object is created using new. They are declared slightly differently from usual methods -- just public, there is no void or double etc. and should be the first methods in the class. A constructor method is used to automatically initialise an object's variables to values of your choice. Here is an example:

    public Complex(double x, double y)
    {
        // initialise class variables to values specified in method call
        realpart = x;
        imagpart = y;
        return;
    }

Enabling Complex objects to be created with any initial values like this:

    Complex z = new Complex(3,4);

The new Complex() you have used before this is a default constructor, which initialises all variables to zero. However, if you write your own constructor like the one above, the default will not exist. It is possible to write more than one constructor for a class, if each takes a different number of arguments. Therefore you could add the default constructor to your classes if you wish -- i.e. in addition to the public Complex(double x, double y) above, the class can also contain:

    // default constructor
    public Complex()
    {
        realpart = 0.0;
        imagpart = 0.0;
        return;
    }


next up previous contents
Next: Using private class variables Up: 8 Object oriented programming Previous: Non-static methods   Contents
RHUL Dept. of Physics