一、java中的interface
java
1、interface中的除非静态、非default方法都是抽象方法,只有定义,没有实现
2、interface中的变量都是常量,被final static修饰
3、interface中可以有default方法,可以有实现,可以被interface的子类引用调用
4、interface中可以有静态方法及实现,可以通过类名直接调用
5、方法及成员都是被public修饰的
6、interface之间才能使用extends,class和interface之间只能使用implement
如
public interface A {
default int hello(){
return 1;
}
String name = "test";
void get();
void set();
static void say() {
System.out.println("say method");
};
int num = 1;
}
typescript
1、interface中的属性和方法不需要修饰符修饰,方法不需要实现,但是要标明返回值
2、interface的属性需要标明属性的数据类型
3、interface中的属性可以是一个赋值为具体的值,实现后也可以更改,ts会报类型错误,需要使用// @ts-ignore忽略错误
4、interface的名称是一个引用类型,不能使用new B() instanceof A这种形式,但是可以用做类型检查
5、interface之间才能使用extends,class和interface之间只能使用implement
如
interface A{
name: string,
age: 1,
say(): void
hello(): void
}
class B implements A{
name = '1';
// @ts-ignore 使用ignore忽略报错
age = 2;
say(): void {
}
}
class C{
get(name: A){ //类型检查
}
}
new C().get('11')//A当作类型检查使用
console.log(new B().name)//
console.log(new B().age)
// new B() instanceof A 不可以这样使用
typescript中的interface如果没有实现,tsc编译后是啥都没有,即便有实现,编译产生的自执行function也是依据class的实现类,所以interface只是typescript语言的语法糖,抽象类也是一样,即便不用interface,也可以用抽象类的方式,实现相同的效果,因此interface是在typescript层面用来做一些属性拼装后的特定类型检查,也可以提供公共的方法,供class去实现