interface 关键字
概述
interface
关键字用于定义接口,是Java实现多重继承的方式。接口定义了一组方法的规范,实现类必须提供这些方法的具体实现。
语法格式
public interface InterfaceName {
// 抽象方法
void method1();
// 默认方法 (Java 8+)
default void method2() {
// 默认实现
}
// 静态方法 (Java 8+)
static void method3() {
// 静态实现
}
// 常量
int CONSTANT = 100;
}
基本用法
// 定义接口
public interface Drawable {
// 抽象方法(隐式public abstract)
void draw();
void resize(double factor);
// 常量(隐式public static final)
String DEFAULT_COLOR = "BLACK";
int MAX_SIZE = 1000;
}
// 实现接口
public class Circle implements Drawable {
private double radius;
private String color;
public Circle(double radius) {
this.radius = radius;
this.color = DEFAULT_COLOR;
}
@Override
public void draw() {
System.out.println("绘制半径为 " + radius + " 的圆形,颜色:" + color);
}
@Override
public void resize(double factor) {
radius *= factor;
System.out.println("圆形大小调整为原来的 " + factor + " 倍");
}
}
public class Rectangle implements Drawable {
private double width, height;
private String color;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
this.color = DEFAULT_COLOR;
}
@Override
public void draw() {
System.out.println("绘制 " + width + "x" + height + " 的矩形,颜色:" + color);
}
@Override
public void resize(double factor) {
width *= factor;
height *= factor;
System.out.println("矩形大小调整为原来的 " + factor + " 倍");
}
}
多接口实现
// 定义多个接口
interface Flyable {
void fly();
double getMaxAltitude();
}
interface Swimmable {
void swim();
boolean canDive();
}
interface Walkable {
void walk();
double getSpeed();
}
// 实现多个接口
public class Duck implements Flyable, Swimmable, Walkable {
private String name;
public Duck(String name) {
this.name = name;
}
@Override
public void fly() {
System.out.println(name + " 正在飞行");
}
@Override
public double getMaxAltitude() {
return 100.0; // 米
}
@Override
public void swim() {
System.out.println(name + " 正在游泳");
}
@Override
public boolean canDive() {
return true;
}
@Override
public void walk() {
System.out.println(name + " 正在走路");
}
@Override
public double getSpeed() {
return 5.0; // 公里/小时
}
}
public class MultiInterfaceExample {
public static void main(String[] args) {
Duck duck = new Duck("唐老鸭");
duck.fly();
duck.swim();
duck.walk();
System.out.println("最大飞行高度: " + duck.getMaxAltitude() + " 米");
System.out.println("能潜水: " + duck.canDive());
System.out.println("行走速度: " + duck.getSpeed() + " 公里/小时");
}
}
默认方法和静态方法(Java 8+)
public interface Vehicle {
// 抽象方法
void start();
void stop();
// 默认方法
default void honk() {
System.out.println("嘟嘟!");
}
default void displayInfo() {
System.out.println("这是一个交通工具");
System.out.println("品牌: " + getBrand());
}
// 静态方法
static void printManufacturer() {
System.out.println("车辆制造商信息");
}
static boolean isValidSpeed(int speed) {
return speed >= 0 && speed <= 300;
}
// 抽象方法
String getBrand();
}
public class Car implements Vehicle {
private String brand;
private boolean isRunning;
public Car(String brand) {
this.brand = brand;
this.isRunning = false;
}
@Override
public void start() {
isRunning = true;
System.out.println(brand + " 汽车启动");
}
@Override
public void stop() {
isRunning = false;
System.out.println(brand + " 汽车停止");
}
@Override
public String getBrand() {
return brand;
}
// 可以重写默认方法
@Override
public void honk() {
System.out.println(brand + " 汽车: 滴滴!");
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
Car car = new Car("丰田");
car.start();
car.honk(); // 调用重写的默认方法
car.displayInfo(); // 调用接口的默认方法
car.stop();
// 调用静态方法
Vehicle.printManufacturer();
System.out.println("速度120是否有效: " + Vehicle.isValidSpeed(120));
}
}
接口继承
// 基础接口
interface Animal {
void eat();
void sleep();
}
// 接口继承
interface Mammal extends Animal {
void giveBirth();
boolean isWarmBlooded();
}
interface Carnivore {
void hunt();
String[] getPreyTypes();
}
// 多接口继承
interface Predator extends Mammal, Carnivore {
void stalk();
double getHuntingSuccess();
}
// 实现继承的接口
public class Lion implements Predator {
private String name;
public Lion(String name) {
this.name = name;
}
@Override
public void eat() {
System.out.println(name + " 正在进食");
}
@Override
public void sleep() {
System.out.println(name + " 正在睡觉");
}
@Override
public void giveBirth() {
System.out.println(name + " 生产小狮子");
}
@Override
public boolean isWarmBlooded() {
return true;
}
@Override
public void hunt() {
System.out.println(name + " 正在狩猎");
}
@Override
public String[] getPreyTypes() {
return new String[]{"斑马", "羚羊", "水牛"};
}
@Override
public void stalk() {
System.out.println(name + " 正在潜行追踪猎物");
}
@Override
public double getHuntingSuccess() {
return 0.3; // 30%成功率
}
}
函数式接口
// 函数式接口(只有一个抽象方法)
@FunctionalInterface
public interface Calculator {
double calculate(double a, double b);
// 可以有默认方法
default void printResult(double a, double b) {
System.out.println("结果: " + calculate(a, b));
}
// 可以有静态方法
static void showHelp() {
System.out.println("这是一个计算器接口");
}
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
// 使用Lambda表达式实现函数式接口
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
Calculator divide = (a, b) -> {
if (b != 0) {
return a / b;
} else {
throw new IllegalArgumentException("除数不能为0");
}
};
// 使用接口
System.out.println("5 + 3 = " + add.calculate(5, 3));
System.out.println("5 * 3 = " + multiply.calculate(5, 3));
System.out.println("15 / 3 = " + divide.calculate(15, 3));
// 调用默认方法
add.printResult(10, 20);
// 调用静态方法
Calculator.showHelp();
}
}
接口作为类型
public class InterfaceAsTypeExample {
// 接口作为参数类型
public static void drawShape(Drawable shape) {
shape.draw();
shape.resize(1.5);
}
// 接口作为返回类型
public static Drawable createShape(String type) {
switch (type.toLowerCase()) {
case "circle":
return new Circle(5.0);
case "rectangle":
return new Rectangle(10.0, 6.0);
default:
throw new IllegalArgumentException("未知的形状类型: " + type);
}
}
// 接口数组
public static void drawAll(Drawable[] shapes) {
for (Drawable shape : shapes) {
shape.draw();
}
}
public static void main(String[] args) {
// 接口引用指向实现类对象
Drawable circle = new Circle(3.0);
Drawable rectangle = new Rectangle(8.0, 4.0);
// 多态调用
drawShape(circle);
drawShape(rectangle);
// 工厂方法返回接口类型
Drawable shape1 = createShape("circle");
Drawable shape2 = createShape("rectangle");
// 接口数组
Drawable[] shapes = {shape1, shape2, circle, rectangle};
drawAll(shapes);
}
}
最佳实践
接口命名约定:
// 行为接口通常以-able结尾 interface Readable { } interface Writable { } interface Comparable { } // 回调接口通常以Listener结尾 interface ClickListener { } interface EventListener { }
接口隔离原则:
// 好的做法 - 小而专一的接口 interface Readable { String read(); } interface Writable { void write(String content); } // 避免臃肿的接口 // interface FileHandler { // String read(); // void write(String content); // void delete(); // void backup(); // void compress(); // }
合理使用默认方法:
interface List<T> { void add(T item); T get(int index); // 默认方法提供便利功能 default boolean isEmpty() { return size() == 0; } default void addAll(T... items) { for (T item : items) { add(item); } } int size(); }
interface关键字是Java面向对象编程的核心特性,它支持多重继承、提供代码复用和实现松耦合设计。