← 返回首页

Java多态:灵活的对象行为

📂 java ⏱ 2 min 350 words

Java多态:灵活的对象行为

概述

多态是指同一操作作用于不同的对象时,可以产生不同的执行结果。Java通过方法重写和接口实现来支持多态,使得程序更加灵活和可扩展。

1. 多态的基本概念

public abstract class Shape {
    protected String color;

    public Shape(String color) {
        this.color = color;
    }

    public abstract double area();
    public abstract double perimeter();

    public void display() {
        System.out.println("颜色: " + color + ", 面积: " + area());
    }
}

public class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    @Override
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}

public class Rectangle extends Shape {
    private double width, height;

    public Rectangle(String color, double width, double height) {
        super(color);
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
}

2. 向上转型与向下转型

public class ShapeTest {
    public static void main(String[] args) {
        // 向上转型
        Shape shape1 = new Circle("红色", 5.0);
        Shape shape2 = new Rectangle("蓝色", 4.0, 6.0);

        shape1.display();
        shape2.display();

        // 向下转型
        if (shape1 instanceof Circle) {
            Circle circle = (Circle) shape1;
            System.out.println("半径: " + circle.area() / Math.PI);
        }
    }
}

3. 多态的实际应用

// 支付接口
public interface Payment {
    boolean pay(double amount);
    String getPaymentMethod();
}

// 微信支付
public class WeChatPayment implements Payment {
    @Override
    public boolean pay(double amount) {
        System.out.println("微信支付: " + amount + "元");
        return true;
    }

    @Override
    public String getPaymentMethod() {
        return "微信支付";
    }
}

// 支付宝
public class AliPay implements Payment {
    @Override
    public boolean pay(double amount) {
        System.out.println("支付宝支付: " + amount + "元");
        return true;
    }

    @Override
    public String getPaymentMethod() {
        return "支付宝";
    }
}

// 支付处理器
public class PaymentProcessor {
    public void processPayment(Payment payment, double amount) {
        System.out.println("使用" + payment.getPaymentMethod() + "处理支付...");
        payment.pay(amount);
    }
}

4. 多态数组

public class PolymorphismArray {
    public static void main(String[] args) {
        Shape[] shapes = new Shape[3];
        shapes[0] = new Circle("红色", 5.0);
        shapes[1] = new Rectangle("蓝色", 4.0, 6.0);
        shapes[2] = new Circle("绿色", 3.0);

        double totalArea = 0;
        for (Shape shape : shapes) {
            totalArea += shape.area();
        }
        System.out.println("总面积: " + totalArea);
    }
}

最佳实践

  1. 优先使用父类或接口类型:提高代码的灵活性
  2. 使用instanceof进行类型检查:向下转型前必须检查
  3. 合理设计抽象层:抽象类或接口定义通用行为
  4. 避免频繁的类型转换:说明设计可能有问题

总结

多态是Java面向对象编程的重要特性,它使得程序可以根据对象的实际类型执行不同的行为。掌握多态的使用,可以编写出更加灵活、可扩展的代码。