什麼是polymorphism?

定義

Polymorphism refers to the ability of different objects to be treated as objects of a common type. It allows a single interface to be used for entities of different types.

白話來說就是,允許同個名子的東西有不同行為。

例子

  • Overloading: 也就是同個Method名,不同Parameters
  • Overriding: 子類覆蓋父類的Method
// Base class
class Shape {
    public double calculateArea() {
        return 0; // Default, will be overridden by subclasses
    }
}

// Subclass 1
class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

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

// Subclass 2
class Square extends Shape {
    private double side;

    public Square(double side) {
        this.side = side;
    }

    @Override
    public double calculateArea() {
        return side * side;
    }
}
Shape circle = new Circle(5.0);
Shape square = new Square(4.0);

double areaOfCircle = circle.calculateArea(); // Calls Circle's calculateArea()
double areaOfSquare = square.calculateArea(); // Calls Square's calculateArea()

由此可以看出,雖然都是calculateArea()卻可以有不同的行為及定義,這就是歸功於OOP的Polymorphism


什麼是polymorphism?
https://f88083.github.io/2023/11/20/什麼是polymorphism/
作者
Simon Lai
發布於
2023年11月20日
許可協議