一:接口
1.1接口的定义
- 是抽象方法的集合,接口通常以interface来声明,一个类通过继承接口的方式,从而来继承接口的抽象方法
- Java 8及以后,还可以包含默认方法和静态方法,不包含方法的实现
1.2 接口的作用
- 解耦:接口定义了对象之间的契约,使得不同类之间的交互更加清晰和灵活。
- 多重继承:通过实现多个接口,一个类可以继承多个接口中的方法,实现类似多重继承的功能。
- 定义规范:接口定义了一组方法的集合,实现了该接口的类必须遵循这些方法的定义。
二:接口的定义
接口使用interface来定义,接口中的方法都是隐式抽象的(不需要abstract关键字),且都是public的(没有明确指定)。
package chapter6;
public interface Myinterface {
//常量定义,默认是public static final的
int AGE = 100;
//抽象方法定义,默认是public的
void method0();
String method1();
default void method2(){
System.out.println("这个是接口的默认方法method");
}
static void method3(){
System.out.println("这个是接口的静态方法method");
}
}
在工具中,接口的角标是I,如下图
三:接口实现
定义Myclass类来实现接口
package chapter6;
public class Myclass implements Myinterface,Interface2{
@Override
public void method0() {
System.out.println("Myclass.method0");
}
@Override
public String method1() {
System.out.println("Myclass.method1");
return "aaa";
}
}
创建运行类InterfaceDemo查看实现效果
package chapter6;
public class InterfaceDemo {
public static void main(String[] args) {
Myclass myclaa = new Myclass();
myclaa.method0();
myclaa.method1();
myclaa.method2();
Myinterface.method3();
}
}
/**
运行结果:
Myclass.method0
Myclass.method1
这个是接口的默认方法method
这个是接口的静态方法method
*/