This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

With this super

Now, let’s learn how to use this and super.

First of all, inside a method, you can call other methods.

In the catchMouse method, call the sayHi method, we can also use the super.sayHi method.

Our cat will have one more attribute than the animal, which is the length of the tail. We want to initialize the cat with a length parameter in addition to name: We can override Animal’s constructor method by adding a constructor method to Cat that says “the constructor of the derived class must contain a ‘super’ call.”

What is a super call? The super call refers to the constructor call on Animal.

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    sayHi() {
        console.log('Hi'); }}class Cat extends Animal {
    tailLength: number;
    constructor(name: string, length: number) {
        super(name);
        this.tailLength = length;
    }
    sayHi() {
        console.log('Meow, I amThe ${this.name}The length of my tail isThe ${this.tailLength}`);
    }
    catchMouse() {
        console.log('Caught a mouse'); }}let a = new Cat('Tom'.10);
Copy the code

Problem: complete the code block so that the result is’ Ta is 10 years old

class Animal {
  protected age: number;
  constructor(age: number) {
    this.age = age; }}class Panda extends Animal {
  private name: string;
  constructor(name: string, age: number) {
    // Complete the code here
    this.name = name;
  }
  public getPandaInfo(): string {
    return `The ${this.name} is The ${this.age} years old`; }}const p = new Panda('Ta'.10);
p.getPandaInfo();
Copy the code

Answer: super (age);

Resolution:

const question = `The ${this.name} is The ${this.age} years old`;
const answer = 'Ta is 10 years old';
Copy the code

“Question” is equivalent to “answer”. So the whitespace operation assigns 10 to age.

The constructor of a subclass needs to contain the constructor call of the parent class. Use the keyword super to access and call the parent class in a subclass.

Panda inherits from Animal, whose constructor is

this.age = age;
Copy the code

An assignment that happens to be age, so super(age) should be written in the margin.

Data: Abstract classes vs interfaces

We know that properties or methods that are common between classes can be abstracted into an interface. Abstract classes are base classes that other classes inherit from and are not allowed to be instantiated. Abstract methods in abstract classes must be implemented in subclasses.

Since both describe the shape of a class, we can use them to type variables in TypeScript, so you might be confused about how they work.

  • An abstract class is essentially an uninstantiable class that implements methods and initializes properties, whereas an interface can only be used to describe an implementation that neither provides methods nor initializes properties.
  • A class can inherit a class or abstract class, but can implement multiple interfaces
  • Abstract classes can also implement interfaces

So when we only need to describe the shape of the class and do not need to implement it in a uniform abstraction, we can use interfaces to describe. If we need to extract common methods and properties for unified implementation and initialization, we should use abstract classes for extraction.

Suppose we wanted to declare a Personal class with age and name attributes, with both say and sayHello methods, and with sayHello always returning ‘Hello’ regardless of instantiation

// Declare the IPerson interface
interface IPerson {
    name: string;age: number; say():void;
    sayHello():string;
}
Declare an AbstractPerson abstract class and implement the sayHello method
abstract class AbstractPerson implements IPerson {
    age: number;
    name: string;
    abstract say(): void;
    sayHello() {
        return 'hello'}}// Extends AbstractPerson abstract class
class Person extends AbstractPerson {
    age: number;
    name: string;
    say() {
        return 'hi'
    }
    sayHello() {
        return 'hello'}}Copy the code

Data: Rewrite vs reload

The concept of overwriting and overloading can sometimes be confused for beginners, but they are two different concepts.

  • Overriding is when a subclass overrides a method inherited from a parent class
  • Overloading means providing multiple type definitions for the same function

Let’s differentiate by an example

class Animal {
    say(word: string) :string {
        returnword; }}class Cat extends Animal {
    // func1 overloads, when the input text is of type number, dividing it by 100 and returning a string with two digits after the decimal point
    func1(text: number) :number;
    func1(text: any) :any {
        if (typeof text === 'number') {
            return (text / 100).toFixed(2)}else {
            return text
        }
    }
    // Overwrite Animal say method
    say(): string {
        return 'Meow'}}Copy the code

Data: Inheritance vs. polymorphism

Inheritance by Inheritance

A subclass inherits its parent class, which has all the features of its parent class and some more specific features

Polymorphism

Inheritance results in related classes that can have different responses to the same method. For example, Cat and Dog both inherited from Animal, but each implemented its own sayHi method. We can call the sayHi method on an instance without knowing whether it is Cat or Dog, and the program will automatically figure out how to execute sayHi.

/ / parent Animal
class Animal {
    sayHi(name: string) :string {
        return `My name is`+ name; }}// Cat is from Animal
class Cat extends Animal {
    sayHi(name: string) :string {
        return 'Meow, MyName is ' + name;
    }
    // Cat implements its own eat method
    eat(){
        console.log('eating fish')}}// Dog is descended from Animal
class Dog extends Animal {
    sayHi(name: string) :string {
        return 'Wang, MyName is '+ name; }}// Multistate, declare anAnimal as Animal. When anAnimal is subclassed by new, their sayHi method returns different content
let anAnimal: Animal;
anAnimal = new Cat();
const tomSayHi = anAnimal.sayHi('Tom'); // Meow, MyName is Tom
anAnimal = new Dog();
const spikeSayHi = anAnimal.sayHi('Spike'); // Wang, MyName is Jeff
Copy the code