我有简单的用例,但至少对我来说似乎很棘手。
我有课
public class Operation {
private int a,b;
public Operation(){
}
public Operation(int a,int b){
this.a=a;
this.b=b;
}
public int calculate()
{
return (a+b);
}
}
和四个扩展Operation
的类public class Addition extends Operation {
public Addition(){
super();
}
public Addition(int a,int b){
super(a,b);
}
public int calculate(int a,int b)
{
return (a+b);
}
}
public class Subtraction extends Operation {
public Subtraction()
{
}
public Subtraction(int a,int b)
{
super(a,b);
}
public int calculate(int a,int b)
{
return (a-b);
}
}
public class Multiplication extends Operation {
public Multiplication()
{
}
public Multiplication(int a,int b)
{
super(a,b);
}
public int calculate(int a,int b)
{
return (a*b);
}
}
public class Division extends Operation {
public Division()
{
}
public Division(int a,int b)
{
super(a,b);
}
public int calculate(int a,int b)
{
return (a/b);
}
}
我的Main方法必须遵循
public class CalculationTest {
public static void main(String[] args) {
Operation op=new Addition(100,200);
System.out.println(op.calculate());
op=new Subtraction();
System.out.println(op.calculate()); //this should print -100 as output
op=new Multiplication();
System.out.println(op.calculate()); //this should print 2000 as output
op=new Division();
System.out.println(op.calculate()); //this should print 0 as output
}
}
我必须得到输出 300 -100 2000 0 但我得到了输出 300 0 0 0
提前致谢
答案 0 :(得分:1)
我必须得到输出300 -100 2000 0但我输出为300 0 0 0
那是因为你没有给他们任何意见。
Operation op=new Addition(100,200);
这有输入并且有效。
op=new Subtraction();
这没有输入,因此值默认为0,结果为0.
如果你想减去两个值,你仍然需要提供它们,试试
op = new Subtraction(100, 200);