源码基于Groovy程序设计一书中的第三章第6小姐
java中的多态
基类
public class Employee {
public void raise(Number amount){
System.out.println("Employee got raise");
}
}
子类
import java.math.BigDecimal;
public class Executive extends Employee {
@Override
public void raise(Number amount) {
System.out.println("Executive got raise");
}
public void raise(BigDecimal amount) {
System.out.println("Executive got BigDecimal raise");
}
}
主类
import java.math.BigDecimal;
public class Test {
public static void giveRaise(Employee employee) {
// 由于是基类的定义,在运行时调用的方法必须接受Number作为参数
employee.raise(new BigDecimal(10000.00));
}
public static void main(String[] args) {
giveRaise(new Employee());
giveRaise(new Executive());
}
}
输出
Employee got raise
Executive got raise
在groovy中使用多态
void giveRaise(Employee employee){
employee.raise(new BigDecimal(10000.00))
}
giveRaise new Employee()
giveRaise new Executive()
输出
Employee got raise
Executive got BigDecimal raise