函数重载用于在同一类中创建具有不同参数列表的同名方法,提高代码可读性和灵活性,但可能导致冲突。函数多态通过覆盖父类方法实现抽象,增强灵活性,但可能导致层次结构复杂和不必要的实现。实际应用中,函数重载更简洁,函数多态更抽象。
Java 中函数重载与函数多态的优劣对比
函数重载
优点:
缺点:
函数多态
优点:
缺点:
实战案例:
假设有一个 AreaCalculator 类,它计算不同形状的面积。
public class AreaCalculator {
public double calculateArea(Rectangle rectangle) {
return rectangle.getWidth() * rectangle.getHeight();
}
public double calculateArea(Circle circle) {
return Math.PI * circle.getRadius() * circle.getRadius();
}
public double calculateArea(Triangle triangle) {
return 0.5 * triangle.getBase() * triangle.getHeight();
}
}函数重载优势:
double area = areaCalculator.calculateArea(rectangle); // 矩形 double area = areaCalculator.calculateArea(circle); // 圆 double area = areaCalculator.calculateArea(triangle); // 三角形
函数多态优势:
Shape 来处理不同类型的形状,代码更抽象。public interface Shape {
double getArea();
}
public class AreaCalculator {
public double calculateArea(Shape shape) {
return shape.getArea();
}
}
public class Rectangle implements Shape {
@Override
public double getArea() {
return getWidth() * getHeight();
}
}
public class Circle implements Shape {
@Override
public double getArea() {
return Math.PI * getRadius() * getRadius();
}
}
public class Triangle implements Shape {
@Override
public double getArea() {
return 0.5 * getBase() * getHeight();
}
}