implements 关键字
概述
implements
关键字用于类实现接口,表示类承诺提供接口中声明的所有方法的实现。
语法格式
class ClassName implements Interface1, Interface2, Interface3 {
// 实现接口中的所有抽象方法
}
基本用法
// 定义接口
interface Drawable {
void draw();
void setColor(String color);
}
interface Resizable {
void resize(double factor);
double getArea();
}
// 实现单个接口
class Circle implements Drawable {
private double radius;
private String color;
public Circle(double radius) {
this.radius = radius;
this.color = "black";
}
@Override
public void draw() {
System.out.println("绘制半径为 " + radius + " 的 " + color + " 圆形");
}
@Override
public void setColor(String color) {
this.color = color;
}
}
// 实现多个接口
class Rectangle implements Drawable, Resizable {
private double width, height;
private String color;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
this.color = "black";
}
@Override
public void draw() {
System.out.println("绘制 " + width + "x" + height + " 的 " + color + " 矩形");
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public void resize(double factor) {
width *= factor;
height *= factor;
System.out.println("矩形调整为 " + width + "x" + height);
}
@Override
public double getArea() {
return width * height;
}
}
public class ImplementsExample {
public static void main(String[] args) {
Circle circle = new Circle(5.0);
circle.setColor("红色");
circle.draw();
Rectangle rectangle = new Rectangle(10.0, 6.0);
rectangle.setColor("蓝色");
rectangle.draw();
rectangle.resize(1.5);
System.out.println("面积: " + rectangle.getArea());
}
}
继承与实现结合
// 父类
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
public void sleep() {
System.out.println(name + " 正在睡觉");
}
}
// 接口
interface Flyable {
void fly();
double getMaxAltitude();
}
interface Swimmable {
void swim();
boolean canDive();
}
// 既继承又实现
class Duck extends Animal implements Flyable, Swimmable {
public Duck(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(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;
}
}
class Penguin extends Animal implements Swimmable {
public Penguin(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + " 企鹅叫声");
}
@Override
public void swim() {
System.out.println(name + " 在水中游泳");
}
@Override
public boolean canDive() {
return true;
}
}
public class InheritanceAndImplementsExample {
public static void main(String[] args) {
Duck duck = new Duck("唐老鸭");
duck.makeSound();
duck.fly();
duck.swim();
duck.sleep();
Penguin penguin = new Penguin("企鹅佩佩");
penguin.makeSound();
penguin.swim();
penguin.sleep();
}
}
接口的多态性
interface Vehicle {
void start();
void stop();
String getType();
}
class Car implements Vehicle {
private String brand;
public Car(String brand) {
this.brand = brand;
}
@Override
public void start() {
System.out.println(brand + " 汽车启动引擎");
}
@Override
public void stop() {
System.out.println(brand + " 汽车关闭引擎");
}
@Override
public String getType() {
return "汽车";
}
}
class Bicycle implements Vehicle {
private String brand;
public Bicycle(String brand) {
this.brand = brand;
}
@Override
public void start() {
System.out.println(brand + " 自行车开始骑行");
}
@Override
public void stop() {
System.out.println(brand + " 自行车停止");
}
@Override
public String getType() {
return "自行车";
}
}
class Airplane implements Vehicle {
private String model;
public Airplane(String model) {
this.model = model;
}
@Override
public void start() {
System.out.println(model + " 飞机启动引擎并滑行");
}
@Override
public void stop() {
System.out.println(model + " 飞机降落并关闭引擎");
}
@Override
public String getType() {
return "飞机";
}
}
public class PolymorphismExample {
// 接口作为参数类型
public static void operateVehicle(Vehicle vehicle) {
System.out.println("操作" + vehicle.getType() + ":");
vehicle.start();
vehicle.stop();
System.out.println();
}
public static void main(String[] args) {
// 接口引用指向实现类对象
Vehicle[] vehicles = {
new Car("丰田"),
new Bicycle("捷安特"),
new Airplane("波音747")
};
// 多态调用
for (Vehicle vehicle : vehicles) {
operateVehicle(vehicle);
}
}
}
函数式接口实现
// 函数式接口
@FunctionalInterface
interface Calculator {
double calculate(double a, double b);
}
@FunctionalInterface
interface Printer {
void print(String message);
}
// 传统类实现
class AddCalculator implements Calculator {
@Override
public double calculate(double a, double b) {
return a + b;
}
}
class ConsolePrinter implements Printer {
@Override
public void print(String message) {
System.out.println("[控制台] " + message);
}
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
// 传统实现方式
Calculator addCalc = new AddCalculator();
Printer consolePrinter = new ConsolePrinter();
System.out.println("5 + 3 = " + addCalc.calculate(5, 3));
consolePrinter.print("Hello World");
// Lambda表达式实现(Java 8+)
Calculator multiplyCalc = (a, b) -> a * b;
Calculator divideCalc = (a, b) -> {
if (b != 0) {
return a / b;
} else {
throw new IllegalArgumentException("除数不能为0");
}
};
Printer logPrinter = message -> System.out.println("[日志] " + message);
System.out.println("5 * 3 = " + multiplyCalc.calculate(5, 3));
System.out.println("15 / 3 = " + divideCalc.calculate(15, 3));
logPrinter.print("操作完成");
// 方法引用实现
Printer systemPrinter = System.out::println;
systemPrinter.print("使用方法引用");
}
}
接口常量访问
interface Constants {
// 接口中的变量默认是 public static final
String DATABASE_URL = "jdbc:mysql://localhost:3306/mydb";
int MAX_CONNECTIONS = 100;
double PI = 3.14159265359;
}
interface MathOperations extends Constants {
double add(double a, double b);
double subtract(double a, double b);
// 默认方法可以访问接口常量
default double calculateCircleArea(double radius) {
return PI * radius * radius;
}
}
class SimpleCalculator implements MathOperations {
@Override
public double add(double a, double b) {
return a + b;
}
@Override
public double subtract(double a, double b) {
return a - b;
}
public void showConstants() {
System.out.println("数据库URL: " + DATABASE_URL);
System.out.println("最大连接数: " + MAX_CONNECTIONS);
System.out.println("PI值: " + PI);
}
}
public class InterfaceConstantsExample {
public static void main(String[] args) {
SimpleCalculator calc = new SimpleCalculator();
System.out.println("加法: " + calc.add(10, 5));
System.out.println("减法: " + calc.subtract(10, 5));
System.out.println("圆面积: " + calc.calculateCircleArea(5));
calc.showConstants();
// 直接访问接口常量
System.out.println("直接访问PI: " + Constants.PI);
}
}
最佳实践
实现所有抽象方法:
interface Shape { void draw(); double getArea(); } class Circle implements Shape { @Override public void draw() { /* 必须实现 */ } @Override public double getArea() { /* 必须实现 */ } }
合理使用多接口实现:
// 好的做法 - 实现相关的接口 class MediaPlayer implements Playable, Controllable { // 实现方法 } // 避免实现不相关的接口 // class MediaPlayer implements Playable, Drawable { }
优先组合而非继承:
// 使用接口实现松耦合 interface Logger { void log(String message); } class Service { private Logger logger; public Service(Logger logger) { this.logger = logger; } }
implements关键字是Java实现多重继承和多态的核心机制,正确使用它可以构建灵活、可扩展的代码架构。