Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
From the author of

A constructor is the method an object executes when it’s created. You can think of a constructor as the “wake up” activity that an object performs when it’s made. The good news is that the current version of Visual Basic supports a constructor in a class module through the Class_Initialize() event procedure. That bad news is that VB presently supports one constructor, and although that constructor can have polymorphic behavior, it is subject to the same constraints and subsequent workarounds as any other function in VB that needs to achieve polymorphism. Java, on the other hand, provides classes with the ability to provide more than one constructor, with each constructor having different argument types and counts depending on the need at hand. Subsequently, each constructor has different behavior. In other words, Java supports parameterized constructors.

Look at the second listing again, and notice that the Musician class supports three constructors. The first constructor does not have any arguments:

public Musician(String instrument){
    Instrument = instrument;
}

The second takes an argument that indicates the type of instrument for the musician:

public Musician(String instrument){
    Instrument = instrument;
}

The last constructor takes two arguments. The first argument indicates the type of instrument for the musician, while the second argument is for the mastery level of the musician.

public Musician(String instrument, int masteryLevel){
    Instrument = instrument;
    MasteryLevel = masteryLevel; 
}

Using parameterized constructor simplifies object declaration. One line of code allows you to create an object and choose the object’s initialization behavior from a variety of options. For example, with the Musician class we can create an object and assign an instrument and mastery level to it using multiple lines of code:

Public Musician m = new Musician();
m.setInstrument(“Cello”);
m.setMasteryLevel(3);

Or we can make the objects and do value assignments using one line of code like so:

Public Musician m = new Musician(“Cello”, 3);

The simplicity is obvious.

Visual Basic 7 plans to support parameterized constructors. As of this writing, the language syntax for implementing them is unavailable.

  • + Share This
  • 🔖 Save To Your Account