Comp 110 Constructors

Constructors

After we have defined a class, we know what that object will look like once it's created, but first it needs to be constructed! (We know what strings and numbers do in theory, but until they are declared and initialized, we can't do anything with them!)

What is a constructor?

A special function that allows us to: 

  1. specify unique initial values of properties upon object construction
  2. require certain properties on initialization

Check out the two examples below:

Example 1: Object Construction

class Mascot {
     name: string = "?";
     school: string = "?";
     species: string = "?";
     yearBorn: number = 0;
}

According to this class definition, we are able to create 'Mascot' objects. Each mascot, on construction, will have default properties: 'name' "?", 'school' "?", 'species' "?", and 'yearBorn' 0...So let's make some mascots!

let rameses: Mascot;
//a new object 'rameses' is declared

rameses = new Mascot();
//a new mascot is constructed!

let theEnemy = new Mascot();

...but right now we dont know anything about Rameses! The default property values are all "?" and 0...what if we wanted to give Rameses some property values? How do we do that without manually assigning each individual property? (as seen below)

// ew this is gross! 

rameses.name = "RAMESES";
rameses.school = "UNC";
rameses.species = "Ram";
rameses.yearBorn = 1789;

theEnemy.name = "The Blue Deveil";
theEnemy.school = "Duke";
theEnemy.species = "Demon";
theEnemy.yearBorn = 1838;

Check out example 2! Which uses a constructor to construct its objects rather than manually assigning all of the properties

Check out the pages on Classes and Properties for more details on how this works!

Now we have fully created a couple Mascot objects, we can now use and manipulate them!

Example 2: Constructor Use

//the class TwitterProfile has 3 parameters and a constructor
class TwitterProfile {
    //properties
     _name: String;
     _followers: number;
     _verified: boolean = false;
  
     constructor(name: string, followers: number, verification: boolean){
          this._name = name;
          this._followers = followers;
          this._verified = verification;

     }//end of constructor

    //methods would go here

}//end of class

let myProfile: TwitterProfile = new TwitterProfile ("Kris", 110, true);
print(myProfile._name + " has " + myProfile._followers "on Twitter!");
print(myProfile._name + "is verified: " + _verified);
//What will be printed? 
//"Kris has 110 followers on Twitter!"
//"Kris is verified: true