# 类与接口

类与接口

前几篇博客说过,接口(Interfaces)可以用于对「对象的形状(Shape)」进行描述。现在主要介绍接口的另一个用途,对类的一部分行为进行抽象。

类实现接口

实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements 关键字来实现。这个特性大大提高了面向对象的灵活性。

基本案例

interface ISing {
  // 这个方法是没有任何实现的
  sing();
}

interface IDance {
  // 这个方法是没有任何实现的
  dance();
}


class P implements ISing { // 人  会唱歌、跳舞
  sing() {
    console.log('人会唱歌');
  }
}

class A implements ISing { // 动物  会唱歌、跳舞
  sing() {
    console.log('动物会唱歌');
  }
}

const per = new P();
const an = new A();
per.sing();
an.sing();

看一下编译完成后的执行结果:

在这里插入图片描述

如果需要通过多个接口约束类,只需要使用逗号分割即可:

interface ISing {
  // 这个方法是没有任何实现的
  sing();
}

interface IDance {
  // 这个方法是没有任何实现的
  dance();
}


class P implements ISing, IDance {  // 人  会唱歌、跳舞
  dance() {
    console.log('人跳舞')
  } 
  sing() {
    console.log('人会唱歌');
  }
}

class A implements ISing, IDance { // 动物  会唱歌、跳舞
  dance() {
    console.log('动物跳舞')
  } 
  sing() {
    console.log('动物会唱歌');
  }
}

const per = new P();
const an = new A();
per.sing();
an.sing();
per.dance()
an.dance()

看一下编译完成后执行结果:

在这里插入图片描述

接口继承

接口与接口之间可以是继承关系:

// 接口继承接口

interface IRun {
  run()
}

interface IWalk {
  walk()
}

// 接口继承其他接口
interface IActive extends IRun, IWalk {}

class I implements IActive {
  run() {
    console.log("run");
  }
  walk() {
    console.log("walk");
  }
}

const i = new I();
i.run()
i.walk()

编译完成后,看一下执行结果:

在这里插入图片描述

接口继承类

常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的。

为什么 TypeScript 会支持接口继承类呢?实际上,当我们在声明一个类时,除了会创建一个类之外,同时也创建了一个类型(实例的类型)。所以我们既可以将它当做一个类来用(使用 new 类名 创建它的实例),也可以将它当做一个类型来用(使用 : 类型当作参数的类型)

案例:

// 创建一个类
class NewPerson {
  name: string
  constructor(name: string) {
    this.name = name
  }
  sayHi(){
    console.log(`Hi, ${this.name}!`) // 正确
  }
}
// 接口继承类
interface IPerson extends NewPerson {
  age: number
}
// 实例化对象
let person1: IPerson = {
  name: '我是ed.',
  age: 25,
  sayHi() {
    console.log(`你好,${this.name}! 今年${this.age}岁了!`)
  }
}
person1.sayHi()

保存编译,查看一下运行结果:

在这里插入图片描述

posted @ 2023-12-26 16:44  我是+V  阅读(1)  评论(0编辑  收藏  举报