Happylab Logo
Published on

Day25 : Learning TypeScript: Class Inheritance、abstract、static

Authors

Day25 : Learning TypeScript: Class Inheritance、abstract、static

Today we continue to take notes on classes; only five days left!

If there are any mistakes, please feel free to leave comments. Thank you!


Inheritance with extends

This is similar to JavaScript, using extends to inherit classes and create subclasses, which can use properties and methods from the parent class. In the following example, we use different parameter types to utilize the parent class's method greet.

class Base {
  greet() {
    console.log("Hello, world!");
  }
}

class Derived extends Base {
  greet(name?: string) {
    if (name === undefined) {
      super.greet();
    } else {
      console.log(`Hello, ${name.toUpperCase()}`);
    }
  }
}

const a = new Derived();
a.greet(); // Hello, world!
a.greet("reader"); // Hello, READER

Public, Private, and Protected

TypeScript can use three access modifiers: public, private, and protected.

  • If none are specified, the default is public.
  • Public properties or methods can be accessed anywhere; by default, all properties and methods are public.
  • Private properties or methods cannot be accessed outside the class in which they are declared.
  • Protected properties or methods are similar to private, but they can also be accessed in subclasses.
class Person {
  public name: string; // Public
  protected age: number; // Protected
  private phone: number; // Private

  constructor(name: string, age: number, phone: number) {
    this.name = name;
    this.age = age;
    this.phone = phone;
  }
  getName(): string {
    return this.name;
  }
  setName(name: string): void {
    this.name = name;
  }
}

class Child extends Person {
  constructor(name: string, age: number, phone: number) {
    super(name, age, phone);
  }
  desc() {
    console.log(`${this.name}${this.age}${this.phone}`);
    // phone is a private property and can only be used within the Person class
  }
}

let child = new Child("iris", 18, 0912345678);
console.log(child.name);
console.log(child.age); // Can only be used within Person and its subclasses; error: Property 'age' is protected and only accessible within class 'Person' and its subclasses.
console.log(child.phone); // Can only be used within the Person class; error: Property 'phone' is private and only accessible within class 'Person'.

Private Constructor

This class cannot be inherited or instantiated:

class Child2 {
  private constructor(public name: string) {}
}

let a = new Child2('iris'); // Error: Constructor of class 'Child2' is private and only accessible within the class declaration.

Protected Constructor

Allows usage in subclasses:

class Person3 {
  public name: string;
  protected constructor(name: string) {
    this.name = name;
  }
}

class Child3 extends Person3 {
  constructor(name: string) {
    super(name);
    console.log(name);
  }
}

let a3 = new Child3('iris');
console.log(a3); // Child3 { name: 'iris' }

Abstract

The abstract keyword is used to define abstract classes and abstract methods.

Abstract classes cannot be instantiated. In the example below, we define an abstract class Animal and an abstract method sayHi. An error occurs when trying to instantiate the abstract class:

abstract class Animal {
  public name;
  public constructor(name: string) {
    this.name = name;
  }
  public abstract sayHi(): void;
}

let b = new Animal('Tom'); // Error: Cannot create an instance of an abstract class.

Abstract methods in an abstract class must be implemented in subclasses:

abstract class Animal2 {
  public name;
  public constructor(name: string) {
    this.name = name;
  }
  public abstract sayHi(): void;
}

class Cat extends Animal2 {
  public sayHi() {
    console.log(`Meow, My name is ${this.name}`);
  }
}

let cat = new Cat('Tom');

Static

Methods marked with the static modifier are called static methods. They do not need to be instantiated and can be called directly through the class:

class Animal3 {
  public name;
  public constructor(name: string) {
    this.name = name;
  }
  static isAnimal(c: object) {
    return c instanceof Animal3;
  }
}

let c = new Animal3('Tom');
let d = Animal3.isAnimal(c);
console.log(d); // true
c.isAnimal(c); // Error: c.isAnimal is not a function

Static Can Also Be Inherited

class Base2 {
  static getGreeting() {
    return "Hello world";
  }
}

class Derived2 extends Base2 {
  myGreeting = Derived2.getGreeting();
}

let derived2 = new Derived2();
console.log(derived2);

Thank you for reading, see you tomorrow!


References

https://willh.gitbook.io/typescript-tutorial/advanced/class https://www.typescriptlang.org/docs/handbook/2/classes.html