一、什么是接口?
如果把抽象类抽象得更加的彻底,可以提取出更为特殊的一种“抽象类”,就是接口。
一个接口只有方法的特征,没有方法的实现;因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。
ps: 在JDK1.8前接口中,所有的方法都是默认公共的抽象方法。 在JDK1.8后,接口就可以出现具体方法(static和default修饰的方法)--使用较少
二、接口的作用
接口是解决Java无法使用多继承的一种手段,可以弥补丰富度,让子类具备更高的丰富度,但是接口在实际中更多的作用是制定标准的。
三、定义
定义接口(interface)的语法和定义类(class)的语法类似,只是使用的关键字不同
// 接口的定义 关键字interface
/*接口名称命名规范 :以 I(interface) 开头,后续再跟大写字母开头的单词*/
public interface 接口名称{
// 方法默认为 public abstract 修饰
返回类型 方法名(参数列表);
//ps:default/static修饰的方法 可以有具体的方法实现
default/static 返回类型 方法名(参数列表){
// 方法实现
}
}
// 接口的实现 implements 关键字
public class 类名 implements 接口名{
// 重写接口的所有抽象方法
}
人和洗衣机都能洗衣服 一个接口就是描述一种能力 所以洗衣服就可以作为一个接口(接口指明了一个类必须要做什么和不能做什么,相当于类的蓝图) 而人类和洗衣机类 都具备洗衣服的能力 接口的作用就是告诉两个类,你要实现我这种接口代表的功能,你就必须实现某些方法 两个类 和 接口之间 叫做实现
public interface IWash {
/** 在接口中的方法 默认是公共的抽象方法
所以可以省略 public abstract */
void washClothes();
}
public class Pepole implements IWash {
@Override
public void washClothes() {
System.out.println("人类 手洗");
}
}
public class WashingMachine implements IWash {
@Override
public void washClothes() {
System.out.println("洗衣机 呼呼机洗");
}
}
public class Test {
public static void main(String[] args) {
//new 一个对象
Mother pepole= new Mother();
//调用 洗衣服 行为
pepole.washClothes();
WashingMachine washingMachine = new WashingMachine();
washingMachine.washClothes();
}
}
四、普通的 类和接口
类和类之间叫做继承(extends),类和接口(interface )之间叫做实现(implements)
接口和类是两个完全不同的概念,类是描述对象的属性和行为
接口一般情况下只包含了一个类需要实现的行为。
相似
1.接口和类都有可以有 任意数量的方法
2.接口的文件类型为.java,接口编译后的文件类型依然为.class文件
区别
1.接口不能实例化
2.接口没有构造器
3.接口中的方法 只有抽象方法 和default或static修饰的具体方法
4.接口中的属性 只能是 public static final修饰的常量属性
5.类不能继承接口的 类只能实现接口(一个类可以实现多个接口)
6.接口支持多继承,一个接口可以继承多个接口
使用接口的好处
1.使用接口可以暴露一个类的某些行为,而不是全部行为。
2.接口还可以强制类去实现该接口的所有方法,可以确保某些方法一定被类实现。
五、综合练习
场景:
奥运会中有多个运动员,他们同时参加一到多项比赛,有些人会跑步、有些人会跳水、有些人会跳高、有些人会射击、有些人会前面的多种。我们应该怎么设计?
分析:
跑步、跳水、跳高、射击 都是种能力 作为接口
运动员作为类 分为几种 跳高运动员 跳水运动员 全能运动员...
类和接口之间 是实现
(一个类可以实现多个接口) 所以全能运动员类 后面可以实现多种能力的接口
接口
public interface IRun {
public void run();
}
public interface IShooting {
public void shooting();
}
public interface IHighJump{
void highJump();
}
public interface IDiving {
void diving();
}
全能运动员类
public class QuanNengPlayer extends Player implements IRun,IShooting,IHighJump,IDiving{
@Override
public void run() {
System.out.println("跑步");
}
@Override
public void shooting() {
System.out.println("射击");
}
@Override
public void highJump() {
System.out.println("跳高");
}
@Override
public void diving() {
System.out.println("跳水");
}
}
测试
public class Test {
public static void main(String[] args) {
QuanNengPlayer qnPlayer = new QuanNengPlayer();
qnPlayer.run();
qnPlayer.shooting();
qnPlayer.highJump();
qnPlayer.diving();
// 全能运动员 参加跑步比赛 我们只关注他的跑步能力 根据接口 只向外部暴露出部分功能
IRun run= new QuanNengPlayer();
run.run();
}
}