Quickly understand TypeScript classes, Abstract classes, inheritance, polymorphism

Posted by schoolmommy on Mon, 24 Jan 2022 11:30:44 +0100

Prior to es6, the implementation of JS usage methods or components required the use of functions, prototypes, and prototype chains. The concept of JS classes was introduced in es6, and we can use and build classes based on object-oriented methods using JS. Writing of ES6 classes is also allowed in TS and eventually compiled as JS code allows in browsers.

1. Class Definition

As with the syntax of other object-oriented languages, a class is defined using the class keyword. this in the class represents the current object itself, as shown below. Name represents the name attribute of the current class.

//Define a Person-like class for'people'
class Person{
        name:string;   //attribute
        constructor(name:string){    //Constructor is called automatically when instantiating a class (initializing data)
             this.name = name;
        }
       eat():string{   //behavior
            return `${this.name}Dry rice`
        }
     }
//Instantiate Person Class
let p = new Person('son of a bitch');
console.log(p.eat())  //Dog eggs are dry

2. Class Inheritance

TS uses the extends keyword inheritance, super() table parent object. After creating a subclass, you first need to call the parent constructor super() to initialize the parent class in the constructor constructor, and then initialize the subclass.
Subclasses can execute parent and subclass methods after inheriting the parent. If the parent's methods are overridden in the subclass, the subclass's methods are executed. (Look up in the prototype chain, find the parent's method if no child's method is found)

//Define a Student subclass to inherit the Person class
class Student extends Person{
		stu_num:number;   //New attributes of subclasses
          constructor(name:string,stu_num:number){
               super(name);  //Constructor to initialize parent class
               this.stu_num = stu_num //Initialize subclasses
         }
       
        study():string{     //New behavior of subclasses
             return `${this.name}Start learning`
        }    
 }
 //Instantiate Person Class
let s = new Student('Xuebao');
//Call method of parent class
console.log(s.eat())  //Xuebao is cooking 
//Call your own method
console.log(s.study())  //Xuebao began to learn

3. Modifiers for classes

Three attribute access modifiers are provided in the TS class

Public: Public is accessible inside, outside and subclasses of the current class (public by default without modifiers)

private: private is accessible inside the current class, but not outside the subclass or class

protected: protected types are accessible within the current class, within subclasses, and outside classes

In the code above, the attributes in the class are public modifiers by default and are accessible both inside and outside the class, including subclasses.
This is a fairly understandable point and should not be redundant.

4. Static properties and methods

Use the static keyword in the class to define whether it is a static property or a static method. Only static attributes within a class can be called inside a static method. Access to static properties and invocation of static methods are called using class names and cannot be called using instantiated objects.

class Person{
        static name:string;   //Static Properties
        constructor(name:string){    //Constructor is called automatically when instantiating a class (initializing data)
             this.name = name;
        }
       static eat():string{   //Static method
            return `${this.name}Dry rice`   //Only defined static properties can be invoked inside a static state
        }
     }
//Call static methods, using class name Person
let p = new Person('son of a bitch');
console.log(Person.name)  //son of a bitch
console.log(Person.eat())  //Dog eggs are dry

5. abstract class

Abstract classes in TS are base classes that provide inheritance from other classes and cannot be instantiated.

Use the abstract keyword to define abstract classes and methods, which can only be placed inside Abstract classes.

An abstract method in an abstract class does not contain a concrete implementation, but is used to constrain the method of the derived class, which must implement the abstract method defined in the abstract class.

//Define an abstract animal as the base class for a specific animal
abstract class Animal{
    name:string;
    
    constructor(name:string){
        this.name=name;
    }
    
    abstract eat():any;  //An abstract method does not contain a concrete implementation and must be implemented in a derived class.
    sleep():void{   //Common methods are not implemented in derived classes
        console.log('Other methods may not be implemented')
    }
}
// var a = new Animal()//Error cannot instantiate abstract objects


//Create a Dog class to inherit the abstract class Animal
class Dog extends Animal{
   
    constructor(name:string){
        super(name)
    }
     //Subclasses of abstract classes must implement abstract methods within abstract classes
    eat(){
        console.log(`${this.name}Eat Bones`)
    }
}

let d=new Dog('Puppies');
d.eat();


Six. polymorphic

Polymorphism is the representation of the same method in no classes. TS defines a method in the parent class that is not implemented, and lets its subclasses inherit it to implement. Thus, methods in each subclass will behave differently. This is polymorphism.
For example, take the example above: Define an Animal parent class and define an eat method without writing a specific implementation, create a subclass Dog to override the eat method, and write a specific implementation in the Dog; Create a subclass Cat to override the eat method and write the specific implementation in the Cat. In this way, eats can take on many forms.

//Define an Animal class
 class Animal{
    name:string;
    constructor(name:string){
        this.name=name;
    }
    eat(){}  //Define an eat without writing a specific implementation
}

//Create a Dog class to inherit Animal
class Dog extends Animal{
    constructor(name:string){
        super(name)
    }
    //Override the eat method and write the implementation
    eat(){
        console.log(`${this.name}Eat Bones`)
    }
}
//Create a Cat class to inherit Animal
class Cat extends Animal{
    constructor(name:string){
        super(name)
    }
    //Override the eat method and write the implementation
    eat(){
        console.log(`${this.name}Eat dried fish`)
    }
}
//Instantiate Dog and Cat classes
let d=new Dog('Puppies');
let c=new Cat('Little cat');
d.eat();   //Dogs eat bones
c.eat();   //Kittens eat dried fish

Topics: TypeScript Class Polymorphism abstract class