首页 经验

Typescript中的类的特征(继承、封装、多态性、抽象)

时间: 2024-10-21 12:26:07

(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)

在 TypeScript 中,类是面向对象编程的基础构造之一。类支持面向对象的四大特征:封装、继承、多态性和抽象。以下是每个特征的详细说明及其示例。


1. 封装(Encapsulation)


封装是将数据(属性)和对数据的操作(方法)结合在一起,并控制数据的访问。通过使用访问修饰符,可以限制属性和方法的可见性。


示例:


typescript

class Person {

    private name: string; // 私有属性

    private age: number; // 私有属性


    constructor(name: string, age: number) {

        this.name = name;

        this.age = age;

    }


    public getDetails(): string { // 公共方法

        return Name: ${this.name}, Age: ${this.age};

    }

}


const person = new Person("Alice", 30);

console.log(person.getDetails()); // 输出: Name: Alice, Age: 30

// console.log(person.name); // 访问私有属性会导致错误


2. 继承(Inheritance)


继承是从已有的类创建新类的机制,子类可以继承父类的属性和方法。TypeScript 使用 extends 关键字进行继承。


示例:


typescript

class Animal {

    protected name: string; // 受保护属性


    constructor(name: string) {

        this.name = name;

    }


    public makeSound(): void {

        console.log(${this.name} makes a sound.);

    }

}


class Dog extends Animal {

    public makeSound(): void { // 重写父类的方法

        console.log(${this.name} barks.);

    }

}


const dog = new Dog("Buddy");

dog.makeSound(); // 输出: Buddy barks.


3. 多态性(Polymorphism)


多态性允许一个方法具有多种表现形式,通常通过方法重写来实现。子类可以重写父类的方法,以提供特定的实现。


示例:


typescript

class Cat extends Animal {

    public makeSound(): void { // 重写父类的方法

        console.log(${this.name} meows.);

    }

}


const animals: Animal[] = [new Dog("Buddy"), new Cat("Whiskers")];


for (const animal of animals) {

    animal.makeSound(); // 输出: Buddy barks. 然后 Whiskers meows.

}


4. 抽象(Abstraction)


抽象是指通过定义抽象类和抽象方法,来隐藏复杂的实现细节。抽象类不能被实例化,可以包含抽象方法,这些方法需要在子类中实现。


示例:


typescript

abstract class Shape {

    abstract getArea(): number; // 抽象方法

}


class Rectangle extends Shape {

    constructor(private width: number, private height: number) {

        super();

    }


    public getArea(): number { // 实现抽象方法

        return this.width * this.height;

    }

}


class Circle extends Shape {

    constructor(private radius: number) {

        super();

    }


    public getArea(): number {

        return Math.PI * this.radius * this.radius;

    }

}


const shapes: Shape[] = [new Rectangle(10, 5), new Circle(7)];


for (const shape of shapes) {

    console.log(Area: ${shape.getArea()}); // 输出每个形状的面积

}


总结


TypeScript 中的类特征:


- 封装:通过访问修饰符控制类的属性和方法的可见性。

- 继承:通过关键字 extends 允许新类继承现有类的属性和方法。

- 多态性:方法的重写使得不同类可以以统一的接口进行操作。

- 抽象:通过抽象类和抽象方法提供一种框架,要求子类提供具体实现。


这些特征使得 TypeScript 更加适合于构建大规模的、可维护的应用程序。


上一个 nodejs搭建一个简单的http服务器过程 文章列表 下一个 图论

最新

工具

© 2019-至今 适观科技

沪ICP备17002269号