类实现接口
- 只要实现的某一个接口, 那么就必须实现接口中所有的属性和方法
错误示例:
interface PersonInterface {
name: string;
say(): void;
}
class Person implements PersonInterface {
name: string = 'BNTang';
}
let p = new Person();
p.say();
正确示例:
interface PersonInterface {
name: string;
say(): void;
}
class Person implements PersonInterface {
name: string = 'BNTang';
say(): void {
console.log(`我的名字叫:${this.name}`);
}
}
let p = new Person();
p.say();
接口继承类
定义一个 Person
类如下:
class Person {
name: string = 'BNTang';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
- 只要一个接口继承了某个类, 那么就会继承这个类中所有的属性和方法
- 但是只会继承属性和方法的
声明
, 不会继承属性和方法的实现
class Person {
name: string = 'BNTang';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
interface PersonInterface extends Person {
gender: string;
}
class Student implements PersonInterface {
gender: string = 'male';
name: string = 'zs';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}, gender = ${this.gender}`);
}
}
let stu = new Student();
stu.say();
- 如果接口继承的类中包含了
protected
的属性和方法, 那么就只有这个类的子类
才能实现这个接口
- 包含
protected
属性的情况
错误示例:
class Person {
protected name: string = 'BNTang';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
interface PersonInterface extends Person {
gender: string;
}
class Student implements PersonInterface {
gender: string = 'male';
name: string = 'zs';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}, gender = ${this.gender}`);
}
}
let stu = new Student();
stu.say();
正确示例:
class Person {
protected name: string = 'BNTang';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
interface PersonInterface extends Person {
gender: string;
}
class Student extends Person implements PersonInterface {
gender: string = 'male';
name: string = 'zs';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}, gender = ${this.gender}`);
}
}
let stu = new Student();
stu.say();
- 包含
protected
方法的情况
错误示例:
class Person {
name: string = 'BNTang';
age: number = 18;
protected say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
interface PersonInterface extends Person {
gender: string;
}
class Student implements PersonInterface {
gender: string = 'male';
name: string = 'zs';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}, gender = ${this.gender}`);
}
}
let stu = new Student();
stu.say();
正确示例:
class Person {
name: string = 'BNTang';
age: number = 18;
protected say(): void {
console.log(`name = ${this.name}, age = ${this.age}`);
}
}
interface PersonInterface extends Person {
gender: string;
}
class Student extends Person implements PersonInterface {
gender: string = 'male';
name: string = 'zs';
age: number = 18;
say(): void {
console.log(`name = ${this.name}, age = ${this.age}, gender = ${this.gender}`);
}
}
let stu = new Student();
stu.say();