package xinguan;
abstract class Operation{ //抽象类
public static double numberA= 0;
public static double numberB = 0;
abstract double getResult(); //抽象方法
}
class OperationADD extends Operation{
@Override
double getResult() {
return numberA+numberB;
}
}
class OperationSUB extends Operation{
@Override
double getResult() {
return numberA-numberB;
}
}
class OperationMUL extends Operation{
@Override
double getResult() {
return numberA*numberB;
}
}
class OperationDIV extends Operation{
@Override
double getResult() {
return numberA/numberB;
}
}
class OperationFactory{
public static Operation createOperate(char operate){
Operation oper = null;
switch (operate){
case'+':
oper= new OperationADD();
break;
case'-':
oper= new OperationSUB();
break;
case'*':
oper= new OperationMUL();
break;
case'/':
oper= new OperationDIV();
break;
}
return oper;
}
}
public class CalculateDemo {
/**
* @param args
*/
public static void main(String[] args) {
Operation operADD = OperationFactory.createOperate('+');
Operation operSUB = OperationFactory.createOperate('-');
Operation operMUL = OperationFactory.createOperate('*');
Operation operDIV = OperationFactory.createOperate('/');
operADD.numberA = 15.0;
operADD.numberB = 3;
System.out.println(operADD.getResult());
System.out.println(operSUB.getResult());
System.out.println(operMUL.getResult());
System.out.println(operDIV.getResult());
}
}
因为抽象类是静态方法 所以 给operADD 那个对象赋值一次就能获得所有结果。要是去掉static 那么就需要每个对象 赋值。现在基本满足你的要求了。