多态
什么是多态?
多态(英语:polymorphism)指为不同数据类型的实体提供统一的接口。 简单来说,所谓多态意指相同的消息给予不同的对象会引发不同的动作。
多态示例
业务场景,使用简单工程实现计算器的例子
类图
运算工厂类
package com.wangwei.polymorphism; public class OperatrionFactory { public static Operation createOperation(String operate){ Operation oper=null; switch (operate) { case"+": oper=new OperationAdd(); break; case"-": oper=new OperationSub(); break; } return oper; } }
运算类
package com.wangwei.polymorphism; public class OperatrionFactory { public static Operation createOperation(String operate){ Operation oper=null; switch (operate) { case"+": oper=new OperationAdd(); break; case"-": oper=new OperationSub(); break; } return oper; } }
加法类
package com.wangwei.polymorphism; public class OperationAdd extends Operation{ @Override public double GetResult() { double result=0; result=super.getNumberA()+super.getNumberB(); return result; } }
减法类
package com.wangwei.polymorphism; public class OperationSub extends Operation{ @Override public double GetResult() { double result=0; result=super.getNumberA()-super.getNumberB(); return result; } }
客户端类
package com.wangwei.polymorphism; public class Client { public static void main(String[] args) { Operation oper; oper=OperatrionFactory.createOperation("+"); oper.setNumberA(1); oper.setNumberB(2); double result=oper.GetResult(); System.out.print(result); } }