接口(Interface)的特点
接口是Java中一种重要的引用类型,它具有以下核心特点:
基本定义
-
使用
interface
关键字声明 -
是一种完全抽象的类(Java 8之前)
-
定义了一组规范或契约,实现类必须遵守
核心特点
-
默认方法抽象(Java 8前)
-
所有方法默认是
public abstract
(可省略不写)
interface Animal { void eat(); // 等同于 public abstract void eat(); }
-
-
不能实例化
// Animal a = new Animal(); // 编译错误
-
实现方式
-
类使用
implements
关键字实现接口 -
必须实现所有抽象方法(除非是抽象类)
class Dog implements Animal { @Override public void eat() { System.out.println("狗吃骨头"); } }
-
-
Java 8后的新特性
-
默认方法(default method):可以有方法实现
interface Animal { default void breathe() { System.out.println("呼吸"); } }
-
静态方法(static method):可以直接通过接口调用
interface Animal { static void info() { System.out.println("动物接口"); } }
-
-
Java 9后的新特性
-
私有方法(private method):接口内部使用
interface Animal { private void internalMethod() { // 实现细节 } }
-
-
成员变量特点
-
只能是
public static final
常量(默认修饰符,可省略)
interface Constants { int MAX_VALUE = 100; // 等同于 public static final int MAX_VALUE = 100; }
-
-
多继承特性
-
类只能单继承,但可以实现多个接口
-
接口可以继承多个接口
interface A {} interface B {} interface C extends A, B {} class D implements A, B {}
-
与抽象类的区别
特性 | 接口 | 抽象类 |
---|---|---|
关键字 | interface | abstract class |
方法 | Java 8前全部抽象 | 可包含抽象和具体方法 |
变量 | 只能是常量 | 可以是普通变量 |
构造方法 | 不能有 | 可以有 |
多继承 | 支持多继承(多实现) | 单继承 |
默认访问修饰符 | 方法默认public | 遵循普通类规则 |
使用场景
-
定义行为规范:如
Comparable
、Serializable
-
实现多态:不同类实现相同接口
-
解耦合:定义模块间的通信契约
-
替代多重继承:通过多实现达到类似效果
-
函数式编程:配合Lambda表达式使用
示例代码
// 现代接口示例(Java 8+)
interface Vehicle {
// 常量
int MAX_SPEED = 120;
// 抽象方法
void start();
// 默认方法
default void stop() {
System.out.println("车辆停止");
}
// 静态方法
static void alert() {
System.out.println("注意安全!");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("汽车启动");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // 汽车启动
car.stop(); // 车辆停止
Vehicle.alert(); // 注意安全!
System.out.println("最大速度: " + Vehicle.MAX_SPEED);
}
}