定義
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
class Shape {
public double calculateArea ( ) {
return 0 ;
}
}
class Circle extends Shape {
private double radius;
public Circle ( double radius) {
this . radius = radius;
}
@Override
public double calculateArea ( ) {
return Math . PI * radius * radius;
}
}
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 ( ) ;
double areaOfSquare = square. calculateArea ( ) ;
由此可以看出,雖然都是calculateArea()
卻可以有不同的行為及定義,這就是歸功於OOP的Polymorphism