OOP - Class, Getters & Setters

Concept

Private vs Public

private - Cannot be directly assigned or read outside of the class, only if there is a get / set specified;

public - Can be directly assigned, even outside of the class.

Example of Email Class

class Test {
	public pubVar: string;
	private priVar: string;
	
	constructor(pubVar: string, priVar: string) {
		this.pubVar = pubVar;
		this.priVar = priVar;
	}
}

const test = new Test('Johnny', 'Test');

test.pubVar // Johnny
test.pubVar = 'Ray' // OK
test.priVar // undefined
test.priVar = 'tseT' // Error ts (2341)

Super and Subclasses

Subclasses are an extension of a Superclass.

Protected vs Private

Syntax

class Animal {
  constructor(public birthDate: Date) { }

}

class Bird extends Animal {
  showBirthDate() {
    console.log(this.birthDate);
	}
}

Adding new Properties

class Animal {
  constructor(protected birthDate: Date) { }
}

class Bird extends Animal {
  constructor(public name: string) {
    super(new Date()); // super() is a reference to Animal()
  }
}