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    

Up until Fall 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.