Search code examples
javainheritancehierarchical

Implementing hierarchical inheritance in java


I have simple usecase but seems tricky to me atleast.

I have class

   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);
    }

}

and four classes that extends 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);
    }


}

and my Main method has to do follow

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


    }

}

I have to get output 300 -100 2000 0 but I am getting output as 300 0 0 0

Thanks in advance


Solution

  • I have to get output 300 -100 2000 0 but I am getting output as 300 0 0 0

    That is because you are not giving them any input.

    Operation op=new Addition(100,200);
    

    This has input and it works.

     op=new Subtraction();
    

    This has no input so the values default to 0 and the result is 0.

    If you want to subtract two values, you still have to provide them, try

     op = new Subtraction(100, 200);