多态
多态
什么是多态
- 实例方法默认就是多态的
- 在运行时根据this来决定调用哪个方法
- 静态方法没有多态
- 参数静态绑定,接受者动态绑定 多态只对方法的接受者有效 或者说,多态只选择接受者的类型,不选择参数的类型
下面的输出到底是什么?
public class ParamFather {}
public class ParamSon extends ParamFather {}
public class Father{
public void print(ParamFather param) {
System.out.println("I am father, param is father.");
}
public void print(ParamSon param) {
System.out.println("I am father, param is son.");
}
}
public class Son extends Father{
@Override
public void print(ParamFather param) {
System.out.println("I am son, param is father.");
}
@Override
public void print(ParamSon param) {
System.out.println("I am son, param is son.");
}
}
public class Main {
public static void main(String[] args) {
Father object = new Son();
ParamFather param = new ParamSon();
object.print(param);
}
}
多态实战:策略模式
public class PriceCalculator {
public int calculate(String strategy, int price, User user) {
switch(strategy) {
case "no discount":
return price;
case "95":
return (int) (print*0.95);
case "vip":
if (user.isVip
}
}
}
利用策略模式重构
public class PriceCalculator {
public int calculate(DiscountStrategy strategy, int price, User user) {
return strategy.discount(price, user);
}
}