Methods that inherit data types from a method before them?

55 Views Asked by At

I would like to know how I can get the return value of a method and use it in another directly following it. For instance let's say I did this:

public Integer multiply(Integer n1, Integer n2){
    return n1 * n2;
}

//I know this is wrong but I don't know what params to put
public Integer add(Integer n1, Integer n2){
    return n1 + n2;
}

multiply(2, 2).add(???????);

In this I want to end up using the 4 from the multiply method as a value, then use the add method to add whatever value I give it to the result of the multiply which is four.

Note: I understand I could do:

add(multiply(2, 2), 3);

but I want to know how to use this format.

What I want to accomplish is:

Integer i = multiply(2, 2).add(5);
System.out.print(i);

to where when I run this the output will be 9 because 2 * 2 = 4 + 5 = 9. Please explain this to me :)

2

There are 2 best solutions below

0
On
Integer i = multiply(2, 2).add(5);
System.out.print(i);

here when you do

 multiply(2, 2) 

it returns an integer and using that return type Integer, you are trying to call `add() method.

but add() method is not available inside Integer class with whatever the signature and intended you are trying to do.

so it complains like add() is not available inside Integer class.

so to achieve it make multiple(2,2) to return your own class and have a result in it.

and then call that add() method using that object easily in the way you want.

The way how you could achive the same is like below

package com.kb;

public class MultipleMethodCalls {

    int result;
    static MultipleMethodCalls m = new MultipleMethodCalls();

    public static void main(String[] args) {


        System.out.println(m.multiply(2, 2).add(3));
    }

    public MultipleMethodCalls multiply(Integer n1, Integer n2){


       m.result= n1 * n2;
       return m;

    }

    //I know this is wrong but I don't know what params to put
    public Integer add(Integer n1){
        return this.result + n1;
    }


}
0
On

Return a reference to the class holding the final value and doing operations on it using operands passed as arguments (see Method cascading and Method chaining), something like that:

public class ALU {

    Integer value = 0;

    ALU mutiply(Integer i1, Integer i2) {
        value = i1.intValue() * i2.intValue();
        return this;
    }

    ALU mutiply(Integer i) {
        value *= i.intValue();
        return this;
    }

    ALU add(Integer i) {
        value += i.intValue();
        return this;
    }

    ALU add(Integer i1, Integer i2) {
        value = i1.intValue() + i2.intValue();
        return this;
    }

    @Override
    public String toString() {
        return Integer.toString(value);
    }

    public static void main(String... args) {
        System.out.println(new ALU().mutiply(2, 2).add(5));
    }
}

The output is 9