Class Constructor


#1

Could anyone help explain to me what exactly a class constructor is? I am a bit confused as to how it is different from a class. Thanks in advance!


#2

A class constructor is the block of code that is run as soon as the class is instantiated. In the case of OO programming, objects are instances of classes. So, when you create an object, i.e., Type myVar = new Type(), the call to new Type() invokes the constructor, and then returns your newly initialized object.

This is where you are able to set initial values, or run preliminary actions that need to happen before an object can become initialized.

Does that make sense?

Here is an example of where a constructor becomes useful:

public class MyType {
  private int anIntegerProperty; // initial value is 0!
  private boolean aBooleanProperty; // initial value is false!
  
  public MyType(int integer, boolean bool) { // here we can specify an integer and boolean default value
                                                                     // for our object
    this.anIntegerProperty = integer; // set the object's integer property to the passed in value
    this.aBooleanProperty = bool; // set the object's boolean property to the passed in value
  }
}

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.