接口(Interface)的特点

接口(Interface)的特点

接口是Java中一种重要的引用类型,它具有以下核心特点:

基本定义

  • 使用interface关键字声明

  • 是一种完全抽象的类(Java 8之前)

  • 定义了一组规范或契约,实现类必须遵守

核心特点

  1. 默认方法抽象(Java 8前)

    • 所有方法默认是public abstract(可省略不写)

    interface Animal {
        void eat();  // 等同于 public abstract void eat();
    }
  2. 不能实例化

    // Animal a = new Animal(); // 编译错误
  3. 实现方式

    • 类使用implements关键字实现接口

    • 必须实现所有抽象方法(除非是抽象类)

    class Dog implements Animal {
        @Override
        public void eat() {
            System.out.println("狗吃骨头");
        }
    }
  4. Java 8后的新特性

    • 默认方法(default method):可以有方法实现

      interface Animal {
          default void breathe() {
              System.out.println("呼吸");
          }
      }
    • 静态方法(static method):可以直接通过接口调用

      interface Animal {
          static void info() {
              System.out.println("动物接口");
          }
      }
  5. Java 9后的新特性

    • 私有方法(private method):接口内部使用

      interface Animal {
          private void internalMethod() {
              // 实现细节
          }
      }
  6. 成员变量特点

    • 只能是public static final常量(默认修饰符,可省略)

    interface Constants {
        int MAX_VALUE = 100;  // 等同于 public static final int MAX_VALUE = 100;
    }
  7. 多继承特性

    • 类只能单继承,但可以实现多个接口

    • 接口可以继承多个接口

    interface A {}
    interface B {}
    interface C extends A, B {}
    
    class D implements A, B {}

与抽象类的区别

特性接口抽象类
关键字interfaceabstract class
方法Java 8前全部抽象可包含抽象和具体方法
变量只能是常量可以是普通变量
构造方法不能有可以有
多继承支持多继承(多实现)单继承
默认访问修饰符方法默认public遵循普通类规则

使用场景

  1. 定义行为规范:如ComparableSerializable

  2. 实现多态:不同类实现相同接口

  3. 解耦合:定义模块间的通信契约

  4. 替代多重继承:通过多实现达到类似效果

  5. 函数式编程:配合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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值