object oriented programming typescript
// Example using an Animal
class Animal {
// We have access modifiers (public, private, protected)
// Each member is public by default
// Below line is equivalent to 'public name: string'
name: string;
// Constructor
constructor(name: string) {
this.name = name;
}
// Function / Method
move(distanceInMeters = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Leg {
// private access modifier
private length: number;
constructor(length: number) {
this.length = length;
}
// Getters
getLength() {
return this.length;
}
// Setters
setLength(newLength: number) {
this.length = newLength;
}
}
// Inheritance - A dog IS AN Animal
class Dog extends Animal {
// Composition - A dog HAS A Leg (really 4, but this will do for explanation purposes :D)
leg: Leg;
constructor(name: string, legLength: number) {
super(name);
this.leg = new Leg(legLength);
}
bark() {
console.log("Woof! Woof!");
}
}
// See it in action!
const dog = new Dog("Buddy", 10);
dog.move(10); // Output - Buddy moved 10m.
dog.bark(); // Output - Woof! woof!
dog.leg.getLength(); // Returns - 10
dog.leg.setLength(15); // Sets leg length to 15
dog.leg.getLength(); // Returns - 15
// Example of inheritance and overriding parent class function/method
class Snake extends Animal {
constructor(name: string) {
super(name);
}
// overrides move function/method in parent Animal class
move(distanceInMeters = 5) {
console.log(`${this.name} slithered ${distanceInMeters}m.`);
}
}
// See it in action!
const snake = new Snake("Slippy");
snake.move(); // Output - Slippy slithered 5m.
snake.move(20); // Output - Slippy slithered 20m.