java中什么是Interface接口,请给个实例!

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

java中什么是Interface接⼝,请给个实例!
1.Interface接⼝的定义和⽤法
先直接上⼤⽩话:马克-to-win:接⼝就是灰常灰常抽象的抽象类,我们可以就像⽤抽象类⼀样⽤接⼝,只不过,interface抽象到不能再抽象了,以⾄于⾥⾯不能有任何⽅法的实现,只能都是空⽅法。

紧接着来个例⼦:
例1.1---
interface OpenClose {
void open();
void close();
}
class Shop_mark_to_win implements OpenClose {
public void open() {
System.out.println("商店开门了---shop open");
}
public void close() {
System.out.println("商店关门了---shop close");
}
}
class Bottle_mark_to_win implements OpenClose {
public void open() {
System.out.println("打开瓶⼦,Open the Bottle");
}
public void close() {
System.out.println("盖上瓶⼦Close the Bottle");
}
}
public class Test {
public static void main(String args[]) {
OpenClose s = new Shop_mark_to_win();
s.open();
s.close();
OpenClose b = new Bottle_mark_to_win();
b.open();
b.close();
System.out.println("-----------------");
OpenClose[] x = { s, b };
for (int i = 0; i < x.length; i++) {
x[i].open();
x[i].close();
}
}
}
从上⾯例⼦看出,interface和抽象类的⽤法⼏乎⼀样,也有动态⽅法调度的概念。

通过运⽤关键字interface,Java允许你定义⼀个接⼝。

接⼝只有⽅法的定义,没有⽅法的任何实现。

那这有什么意义呢?马克-to-win:接⼝就像⼀个服务合同。

接⼝只关⼼必须得⼲什么⽽不关⼼如何去实现它。

有意义吗?有意义。

马克-to-win:⽐如我们的软件经理总是关⼼⼯程师应该⼲什么?但软件经理从来不具体⾃⼰⼲什么事情,具体⼲什么事的⼯作留给⼯程师们去⼲。

这种分⼯协作,带来了软件的巨⼤进步。

国家部门只关⼼企业们应该做什么,但国家部门本⾝不做任何企业应该做的⼯作。

分⼯协作带来了社会的巨⼤进步。

Interface is like a contracct
Interface focuses on behavior without being concerned about implementation details.
Interface totally isolate what must to do and how to do it.。

相关文档
最新文档