本帖最后由 杨博 于 2013-3-15 20:24 编辑
- /*
- 关于运算操作程序
- */
- class Test8
- {
- public static void main(String[] args)
- {
- int a=4;
- int b=1;
- Operation op=OpeationFactory.getOperation('-');
- int result=op.oper(a,b); 。
- System.out.println(result);
- }
- }
- class OpeationFactory
- {
- public static Operation getOperation(char c){
- Operation op=null;
- switch(c){
- case '+': op=new Add();break; <FONT color=red> //这块的作用,为什么是Operation类,有什么用,不能设置为calss Add吗?</FONT>
- case '-': op=new Sub();break;
- case '*': op=new Mul();break;
- case '/': op=new Div();break;
- case '%': op=new Mod();break;
- }
- return op;
- }
- }
- abstract class Operation
- {
- abstract int oper(int a,int b);
- }
- class Mod extends Operation
- {
- int oper(int a,int b){
- return a%b;
- }
- }
- class Add extends Operation
- {
- int oper(int a,int b){
- return a+b;
- }
- }
- class Sub extends Operation
- {
- int oper(int a,int b){
- return a-b;
- }
- }
- class Mul extends Operation
- {
- int oper(int a,int b){
- return a*b;
- }
- }
- class Div extends Operation
- {
- int oper(int a,int b){
- return a/b;
- }
- }
复制代码 问题见代码红色部分,这块说用到父类引用指向了子类对象,具体在代码中是怎么做的,求指导
|