Comp 110 Classes/Objects Overview

Classes and Objects

class is a blueprint for an object. An object's class is what defines its properties and capabilities.

Classes are made up of 3 main parts:

1. Properties

Properties are the type of data an object can hold inside of it or encapsulate. Every object of the same class will have the same properties and these properties have the same default values.

2. Constructors

Constructors are called with the new keyword in order to create new instances of the class. The constructor is signified with the constructor keyword inside the class.

3. Methods

Methods define an object's capabilities. We have already encountered some examples of methods when working with strings.

Syntax for class declaration and definition: 

class <Name> {    
    // Properties    
    <propertyName>: <propertyType>;   
  
    // Constructor    
    constructor (<parameters>) {        
        // elided    
    }    
    // Methods    
    <methodName>(<parameters>): <returnType> {        
        // elided    
    }
}

Until closer to spring break, we will only be looking at objects as structs, however. So if you are looking at this page and have no idea what a constructor or a method is, fear not! You will get there soon. When we say we are dealing with "objects as structs," that means our class is defining a composite data type that will group a list of variables to be kept together in memory.

For example: A Student

class Student {    
    name: string = "Jane Doe";    
    credits: number = 0;    
    mealPlan: boolean = true;
}

This Student class will look similar to the classes you will work with the first half of the semester. It just pulls together 3 different variables that are all associated with a single individual Student. Every Student object you instantiate will have these 3 properties.

Creating Objects

Initializing a composite data type requires constructing a new object. You will write the new keyword followed by class name followed by empty parenthesis. For example:

aStudent = new Student();

When this expression is evaluated, the processor constructs a new object in heap memory with space allocated for each property. It also assigns the default values to each property specified in the class. Finally a reference to the object is returned and assigned to the proper value.