The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IX - CONSTRUCTORS

Step 34: What is a Constructor?


A Constructor as the name implies is a method utilized to create or build objects of its class.

Every class has an implicit and default Constructor. This Constructor is invisible, that is, is not written down, but it's part of the class. Every time we instantiate a class to create an Object, we are using a Constructor of that class.

The Constructor does not have to be implicit or default. We can write an actual Constructor to be used for building Objects of its class.

When we explicitly write a Constructor, it's as writing a method with the same name of the class, but with no return parameters (not even void). It can be argued that it returns the instance of its class.

When we instantiate a class by creating an Object we are using a Constructor.

See below the Instantiation of the StringBuffer class: StringBuffer msg = new StringBuffer(); // here StringBuffer() is the constructor. Notice the set of parentheses, as the Constructor is a method.

We can also have Constructors to which we can pass parameters.

StringBuffer msg = new StringBuffer("Hello"); // here the Constructor accepts a String parameter.
A Constructor is a special method with the same name of the class, and no return parameter. It is invoked when using the 'new' operator.

Example of an explicit Constructor defined within the Exercise class. class Exercise
{ public static void main(String[] args)
{ // code goes here for the main method }
Exercise() // this is the Constructor Definition
{ // code goes here for this Constructor }
}



Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IX - CONSTRUCTORS

Step 35: Why Constructors?


In general a Constructor is used to create an Object of a class.

The other two main reasons for having Constructors are:
  • Object Initialization
  • Communication among Objects of different classes.

Object Initialization:

As we create Objects we can utilize the Constructor to initialize the Object to a particular state. This is convenient as the Constructor controls what initialization is done upon the Object.

Example: (Object Initialization) class Exercise
{ public static void main(String[] args)
{ int numberQuestions = 5;
Exercise test = new Exercise(numberQuestions);
// The 'test' Object is initialized to 5 questions when Constructor below is implemented.
}
Exercise(int tmpNumber) // an 'int' parameter is passed to the Constructor
{ numberQuestions=tmpNumber;
// Object is initialized to number of questions as stated in the calling unit, the 'main'.
}
}

Communication among Objects:

Constructors are also very useful when we want to communicate among Objects of different classes. For example, a Constructor can be used to instantiate an Object of another class, and pass to it an instance of its class.

We will use the 'this' operator in a later Step, and we will be having 2 classes. Two Objects of those 2 classes will be created and an Object of one class is passed to the other class via the Constructor.


Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IX - CONSTRUCTORS

Step 36: Order of Call for class(static) and Instance Objects


Order of Call for class(static) and Instance Objects

Class (static) Objects or variables are first implemented before Instance ones.

If within a class we have a class Object initialized with the new operator, and an Instance Object also initialized by the new operator, the Constructor of the class (static) Object is invoked first, followed by the Constructor of the Instance Object. If the class is instantiated, then its Constructor is invoked after those other Constructors are called.

To illustrate this, let's look at the following Example:

class Quiz
{ static Message greeting = new Message(); // this is a static 'Message' class instantiated.
Note farewell = new Note(); // this is an Instance 'Note' class instantiated.

public static void main(String[] args)
{ Quiz test = new Quiz(); // here we instantiate our Quiz class }

Quiz()
{ System.out.println("This is the Quiz Constructor."); }
}

class Note
{ Note()
{ System.out.println("This is the Note Constructor"); }
}

class Message
{ Message()
{ System.out.println("This is the Message Constructor"); }
}

When above code is executed, the order of Constructor calling is: first the Message Constructor, then the Note Constructor and last the Quiz Constructor.



Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IX - CONSTRUCTORS

Step 37: Constructor Overloading


Constructor Overloading

The same way as we have overloaded Methods, we can overload Constructors.

It makes sense to overload Constructors. If we have more than one Constructor, we can have more options to initialize Objects of a class. For instance, we can initialize an Object by using its default Constructor, or by using a Constructor to which we pass desired arguments.

If we look at some of the JAVA classes, we'll see that many of them have more than one Constructor. The class 'StringBuffer' for instance, has 3 Constructors: one default, one that allows to pass an integer (which represents the size of the Object), and one that allows to pass a String.

An Example of Constructor Overloading: class Exercise
{ int numberQuestions;
public static void main(String[] args)
{ Exercise assignment;
assignment = new Exercise() ; // Object 'assignment' is initialized with no arguments

Exercise classWork;
classWork = new Exercise(4); // Object 'classWork' is initialized with 4 questions.
}
Exercise() // default Constructor with no arguments
{ // code goes here. }
Exercise(int tmpNumberQuestions) // Constructor with an argument
{ numberQuestions = tmpNumberQuestions; } }
}


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION IX - CONSTRUCTORS

Step 38: The 'this' reference


The 'this' reference means "an instance of this class". It's used in Instance methods as well as in Constructors.

The 'this' reference is used implicitly when invoking instance methods or instance variables of a class. In that case, writing 'this' is optional.

Example: class Exercise
{ int number;
void setProcess() // setProcess() method defined
{ this.number = 4;          // the reference 'this' is implicit and is optional here.
this.setNumber(number); // the reference 'this' is implictly and is optional here.
}
void setNumber(int tmpNumber) // setNumber method defined
{ // code goes here }
}


There are many ways of using the 'this' reference explicitly:
  • As an argument (in an Instance Method or in a Constructor)
  • As a return value within an Instance Method
  • To invoke a Constructor in a class from another Constructor in the same class
  • For resolving names conflict between local and Instance variables

  • 'this' as an argument

    The 'this' reference can be passed in a Constructor parameter to initialize an Object of an outside class.

    The Example below illustrates using a Constructor to communicate with an Object of a different class.

    Example: (Communicating between 2 Objects via Constructors) class Exercise
    { Exercise() // The code below is used to instantiate the Lecture class.
    { Lecture seminar;
    seminar = new Lecture(this);
    // here the Object of the class Exercise is passed
    // to initialize the Object 'seminar' of the Lecture class
    }
    }
    class Lecture
    { Exercise symposium;
    Lecture(Exercise object) // here the Object of the class Exercise is received.
    { symposium = object; }
    }
    A similar case is using 'this' as an argument in a Method parameter to pass an Object of its class to another Method of another class.

    Example: (Communication between 2 Objects via Methods) class Exercise
    { void setExercise() // The code below is used to instantiate the Lecture class.
    { Lecture seminar = new Lecture();
    // above the class Lecture is instantiated (Object 'seminar' is created.)

    seminar.processLecture(this);
    // above the Object of the Exercise class is passed
    // to the Method processLecture of the Lecture class.
    }
    }
    class Lecture
    { Exercise symposium;
    void processLecture(Exercise object) // here the Object of the class Exercise is received.
    { symposium = object;
    // code continues....
    }
    }

    'this' as a return value within an Instance Method

    Example: class Exercise
    { Exercise test() // Instance method that returns an Exercise class objet.
    { // code goes here
    return this; // returns this class (Exercise class) Object.
    }
    }

    'this' to invoke a Constructor from within a Constructor

    The 'this' reference can be used in a Constructor to call another Constructor of the same class. It is used when Constructors are overloaded. (multiple Constructors in the class)

    When used this way, it is required that 'this' be coded on the first line in the Constructor.

    This technique is very useful when creating Objects that need to be initialized by more than one Constructor. In this case, 'this' is followed by a set of parentheses the same way as if a Constructor would be invoked. The examples below illustrates its use.

    Example: class Exercise
    { Exercise() // A Default Constructor with no arguments
    { // code goes here }
    Exercise(int tmpNumber) // a Constructor with one argument
    { this(); // it invokes above Constructor
    // code continues here
    }
    }
    Another Example: class Exercise
    { Exercise(int tmpNumber) // A Constructor with one argument
    { // code goes here }
    Exercise() // a Default Constructor with no argument
    { this(80); // invokes above Constructor and pass an argument 'int' to it.
    // code continues here
    }
    }

    'this' to avoid name conflict

    Another way of utilizing 'this' is in the case where the Local Variables of a method or a Constructor, and the Instance Variables are named the same by the programmer.

    Sometimes the programmer like to associate the temporary Local Variables with the Instance Variables used by the Object, and one way of doing that is by naming them the same. If that's the case, then a way to distinguish the variables is by having the reference 'this' in front of the Instance Variable, and use of the dot for reference.

    See Example below: class Exercise
    { int number; // 'number' here is the Instance Variable
    void setProcess(int number) // 'number' here is the Local Variable
    { this.number = number; // Instance Variable number = number
    // if 'this' is not used it will still compile,
    // but result is not what you may expect.
    }
    }


    Click here to go to the JAVA Mini-Course page