Introduction to Object Oriented Programming

Overview

What is procedural programming?

Why do we use procedural programming?

Why do we not use procedural programming?

Why do we use OOP?

Object Oriented Programming (OOP)

The 3 aspects of an object



Classes

Class naming conventions



Encapulsation

Encapsulation

Sample

class Person{ // class signature
    // constructor
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
let leon = new Person("Leon", "Hunter", 27);

Instance-Functions (Methods)

Instance-Variables (Fields)



Constructors

Nullary Constructor

Sample

class Person{ // class signature

	constructor(){ // constructor signature
        console.log("A person object has been created");
    }
}
let person = new Person();
A person object has been created

Default Constructor

Sample

class Person{ // class signature
    // no constructor defined

    sayHello(){
        print("Hello");
    }
}
let person = new Person();
person.sayHello();
Hello

Non-nullary Constructor

Sample

class Person{ // class signature
    // constructor
    constructor(firstName, lastName, age){
        this.firstName = firstName;    
        this.lastName = lastName;
    }
}
let leon = new Person("Leon", "Hunter", 27);


Setters
(Mutators)

Sample

class Person{  // class signature
    // constructor
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    setFirstName(newFirstName){
        this.firstName = newFirstName;
    }

    setLastName(this. new_lastName){
        this.firstName = new_lastName;
    }
let leon = new Person("Leon", "Hunter", 27);
let bobFirstName = "Robert";
leon.setFirstName(bobFirstname);

Getters
(Accessors)

Sample

class Person{ // class signature
    // constructor
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    setFirstName(newFistName){
        this.firstName = newFirstName;
    }

    setLastName(newLastName){
        this.firstName = newLastName;
    }

    getFirstName() {
        return this.firstName;
    }

    getLastName() {
        return this.lastName;
    }
}
let leon = new Person("Leon", "Hunter", 27);
let bobFirstName = "Robert";
leon.setFirstName(bobFirstName);
let newFirstName = leon.getFirstName();
print(newFirstName);
Robert