Constructors

A Constructor Example Summary
Practice Exercise

Learning Outcomes

On completion of this section you will know

Download pdf version

Introduction

When we create an object of a class we may occasionally wish to automatically give values to some or all of the variables of that object. Up to now the only way we had for doing that was to call one or more of the object’s set methods.  This is hardly automatic, however.  In object oriented programming the standard way of automatically updating an object’s variables is to use constructors.

A constructor is a method that runs automatically once an object of a class is created. The user cannot stop it from running, nor can it be made to run again – it runs only once during the lifetime of the class.

Apart from the fact that the user cannot control its running a constructor is similar to normal methods, including its ability to be overloaded.

An Example of a Constructor

Go to top

Listing 7.1 below illustrates the use of an overloaded constructor.  Apart from the inclusion of constructors the rest of the code is identical to Listing 6.3, and therefore only part of the code is included here.

Listing 7.1

 1

public class Pay

 2

{

 3

  private double hours, rate, gross, tax, nett;

 4

  private boolean validHours, validRate, calculateOK;

 5

  public Pay()

 6

  {

 7

    hours = 0;

 8

    rate = 0;

 9

    validHours = false;

 10

    validRate = false;

 11

    calculateOK = false;

 12

  }

 13

  public Pay(double h, double r)

 14

  {

 15

    setHours(h);

 16

    setRate(r);

 17

    calculate();

 18

  }

 19

  public void setHours(double h)

 20

  {

 21

    if((h>=5) && (h<=60))

 22

    {

 23

      hours = h;

 24

      validHours = true;

 25

    }

 26

    else

 27

      validHours = false;

 28

  }

 29

  public void setRate(double r)

 30

  {

 31

    if((r>=8) && (r<=50))

 32

    {

 33

      rate = r;

 34

      validRate = true;

 35

    }

 36

    else

 37

      validRate = false;

 38

  }

           

The first constructor spans lines 5 – 12. The first thing we notice about it is that it has the same name as the class that contains it.  Its other feature is that it has no return type. Other than that it looks like any normal method, and it behaves like one as well.  All it does in this case is to initialise hours and rate to zero and sets all of the boolean variables to false.  In programming jargon, it means that it intitialises the variables.

A more useful version of the constructor is the one that spans lines 13 – 18.  This is passed two arguments for hours and rate.  Thus at line 15 the value of the first argument is passed on to setHours and at line 16 the second argument is passed on to setRate.

With values in the variables hours and rate we can call the calculate method to process the data. Thus there is no need for us to initialise any of the object’s variables since the two set methods and the calculate method will do that for us.

In Listing 7.2 below is our modified main method for calling the second constructor of Pay

Listing 7.2

 1

public class Untitled1

 2

{

 3

  public static void main(String[] args)

 4

  {

 5

    Pay p;

 6

    p = new Pay(30,10);

 7

    System.out.println("Hours " + p.getHours());

 8

    System.out.println("Rate " + p.getRate());

 9

    System.out.println("Gross " + p.getGross());

 10

    System.out.println("Tax " + p.getTax());

 11

    System.out.println("Nett " + p.getNett());

 12

  }

 13

}

 

The first new thing we notice about this is the creation of the object of Pay at line 6.  After the name of the class we have two numbers between the brackets.  This means that the second constructor of the class will be called – that is the constructor that spans lines 13 – 18 of Listing 7.1. Here 30 and 10 will be copied into the arguments h and r and then the rest of the constructor will be executed as explained before.

Because of the fact that the second constructor will both receive the values for the hours worked and the hourly rate and that it will eventually call the internal method for performing the calculation there is no need to pass any further information to the object and thus all we need to do is to simply read the results of the calculation and display them.  This we do at lines 7 – 11.

Summary

Go to top

A constructor is a method that runs automatically when we create an object of a class. In Java a constructor has the same name as the class that contains it. Like other methods it can be overloaded. Unlike other methods it has no return type and it cannot be called from a regular method.

Practice

Go to top

Copy listings 7.1 and 7.2 into your computer, then compile and run them.  Trace the running of your programme. Alter listing 7.1 so that the first constructor is called. Notice that when you do this you must separately supply values for the hours and rate and that you also have to call the calculate method separately.


Exercises

Go to top

Exercise 7.1

1)      What is a constructor?

2)      What are the similarities between a constructor and regular methods?

3)      What are the differences between a constructor and regular methods?

4)      Suggest two uses for a constructor.

Exercise 7.2

Alter Exercise 6.2 so that the class Sale has an overloaded constructor. The first constructor takes no arguments and simply initialises all numeric private data members to zero and the Boolean variable to false.

The second constructor will have two arguments to carry the values for the lawnmower code and the amount sold.  It will perform the following actions:

call the set method of the amount sold to place the contents of the appropriate argument in that data member

call the set method of category code to validate that value and if appropriate place it in the appropriate data member

Call the method calculate.

See Listing 7.1 for how to do this.

Next modify your main method so that when an object of Sale is created the values for the lawnmower category and the amount sold are passed to the constructor.

See listing 7.2 for how to do this