5.14.2. Constructors


Constructors

Unfortunately, our PairOfInts class is not useful because it is not possible to create an object of class PairOfInts. Let's change or viewpoint and think of a class as an object factory. The factory creates object using constructors. A constructor looks a bit like a method, but it its heading only shows (1) the name of the class and (2) the parameters to the constructor. Within the constructor, refer to the object's variables by their names. Here is an improvement of class PairOfInts that has a constructor that sets the a and b variables to 0.

  class PairOfInts
  {
     public int a;
     public int b;

     PairOfInts()
     {
        a = 0;
        b = 0;
     }
  }
Use a constructor with new. In a method in some other class, you can write
  PairOfInts p = new PairOfInts();
  p.a = 50;
  p.b = 75;
You do this so that you can treat p as a single thing. For example, method
  static int getA(PairOfInts p)
  {
    return p.a;
  }
takes a parameter of type PairOfInts.


Multiple constructors

A class can have more than one constructor. Here is an improvement of class PairOfInts that has a constructor that initializes the a and b variables in a way given by its parameters.

  class PairOfInts
  {
     public int a;
     public int b;

     PairOfInts()
     {
        a = 0;
        b = 0;
     }

     PairOfInts(int aval, int bval)
     {
       a = aval;
       b = bval;
     }
  }

Notes about constructors

  1. If a constructor does not initialize a variable whose type is a primitive type, that variable is automatically initialized to 0. If the variable's type is a class, then the variable is initialized to null.

  2. Be sure that a constructor's parameter does not have the same name as one of the class's varaibles. If that happens, then the constructor has no way to refer to the variable.