Typescript: abstractclass介绍及应用实例

233 阅读2分钟

在这篇博文中,我们将学习Typecript中的抽象类教程

它是面向对象编程的概念之一。其他概念包括多态性封装接口

Typecript中的抽象类

Typescript支持使用类、接口和抽象类的面向对象编程概念。用抽象关键字定义的类称为抽象类。它被用来提供一个抽象的

这些可能不是创建的实例,而是通过扩展抽象类创建的实例。抽象方法包含一个签名,而不是方法实现。

语法

abstract class abstractclass{  
}  

类型描述 抽象方法

没有实现或主体的方法被称为抽象方法。它只包含方法的签名。抽象方法可以通过附加abstract关键字来声明,这个方法的实现可以由扩展这个抽象类的类来完成,如果抽象方法被声明在一个类中,该类必须用abstract关键字来声明。抽象类包含抽象方法和非抽象方法。

语法

abstract method(): returntype;  

例子

一个抽象类被声明为有一个抽象方法

abstract class Employee {  
    constructor(public name: string,public role: string) {  
    }  
  
    getName(): void {  
        console.log("name: " + this.name);  
    }  
  
    abstract getRole(): void; //Abstract method must be implemented in subclasses  
}  

现在创建一个抽象类的实例,它抛出了编译错误 不能创建一个抽象类的实例

let employee: Employee; // It is valid as instance reference creation  
employee = new Employee("Kiran",'Developer'); // compilation error:Can not create an instance of an  abstract class  

扩展抽象类 - 继承实例

一个抽象类可以像普通类一样被子类扩展,需要为抽象方法提供一个实现。 在下面的例子中,创建了一个子类的实例,你可以调用抽象类的所有方法。

class HrEmployee extends Employee {  
  
    constructor(public name: string,public role: string) {  
        super(name,role); // Construtor has to call super()  
    }  
  
    getHRRoles(): void {  
        console.log(name+'has an '+this.role);  
    }  
  
    getRole(): void {  
        console.log("HR Manager");  
    }  
  
}  
  
let employee: Employee; // It is valid as instance reference creation  
employee = new HrEmployee('kiran','hrmanager');   
employee.getHRRoles(); // Compilation error as getHRRoles() method does not exist on abstract class  
employee.getName();  

抽象属性和get/set方法

一个抽象类也可以声明抽象成员变量,也可以使用set和get访问器类型脚本声明抽象方法。

abstract class Parent {  
    abstract name: string;  
    abstract get value();  
    abstract set value(v: number);  
}  

抽象类实现接口

抽象类实现了接口,需要提供一个抽象方法,否则会出现错误类'MyClass'错误地实现了接口'MyInterface'。

  
  
interface MyInterface {  
    myMethod();  
}  
abstract class MyClass implements MyInterface {  
       abstract  myMethod();  
  
}  

Typecript中的抽象静态方法

抽象方法不应该与静态修改一起使用。下面的例子代码是不允许的,因为它给出了一个错误,静态修改器不能与抽象修改器一起使用。

  
  
abstract class MyInterface {  
   abstract static myMethod();  
}