Comp 110 Classes: Properties

Properties

Classes have properties. Each object made from a class will have all the properties established in that class. We define properties the same way we define variables, just without the let keyword. We still give them a type, and when we declare them, we'll give them a default value. Here's what this would look like inside a class:

class <ClassName> {
    <propertyName>: <type> = <default value>;
    // ...
}

Some examples:

class ordinaryClass {
    stringProperty: string = "";
    numberProperty: number = 0;
    booleanProperty: boolean = false;
}

Here, we give default values as an empty string "", 0, and false.

Another example:

class TarHeel {
    name: string = "";
    studentPID: number = 0;
    hatesDook: boolean = true;
}

 The properties declared inside the body of the TarHeel class are name, studentPID, and hatesDook. Every TarHeel object we make will have these properties.

Within this class, we've set default values for each property. Each new TarHeel object we make will have properties that start with these default values ("" for name, 0 for studentPID, and true for hatesDook), but we can change the values for each object's properties later if we want.

Let's make a TarHeel object:

let ramster: TarHeel = new TarHeel();

Great! Since ramster is now a TarHeel object, it automatically has the properties set up in the class declaration with the default values we provided there. So, the name property of our ramster object is currently "", the studentPID property has the default of 0 still, and hatesDook is true. We know our ramster object should have an actual name instead of the empty string "", so let's change it to make it what we want.

Assigning and Accessing Properties

We'll use the assignment operator (=) to change the properties in our ramster object so they can have their own unique values. 

ramster.name = "Rameses";
ramster.studentPID = 123456789;

When we want to change the values of the properties that our ramster object has, we've got to be sure we tell the computer we're only talking about our specific ramster object. That's why we say ramster.name when we change the value of the name property. We don't want to change the name of any other TarHeel object to "Rameses"; we only want to change that property for our specific object.

In general, when we want to change properties of our objects so they don't always have the default values, we follow this format:

<object>.<property> = <value>;

Now that we have the ramster object of type TarHeel, we can do different things with it. To access an object's properties, we first have to say what object we're talking about, just like we do when we assign values to properties. Here's an example (assuming we imported print from the introcs library):

print("Welcome to UNC, " + ramster.name + "!!!");
// prints: Welcome to UNC, Rameses!!!

Here, we're reading the name property of the ramster object in our print statement.