Just out of curiosity! If I got a method that takes user input and stores it as an int variable. Is there a way I could pass those methods on to another method? I know about return values, but that is only (as far as I know) for one single number,object etc…
The easy way would of course to just to do calculate the result within this method, but is it possible somehow to pass these ints: a,b. To another method, without using global variables? I am just wondering.
private void takeInput(int valueA, int valueB){
println("Enter a number: (a) and (b), to calculate the Phytagoeran Theorem: (c)\n");
int a = readInt("a:");
println("you set the value of a to: "+a +"\n\nNext! set the value of b");
int b = readInt("b:");
println("you set the value of b to:"+b);
}
The question is unclear, but I wonder whether you’ve invented “dependency injection”?
The first part of the puzzle is that, yes, a method can return more than one value, by wrapping them in an object.
And with that you can do:
(Note that public fields are not usually considered good style – I use them here because the code is shorter. In real code use getters and setters).
That might be all the answer you need. But you ask:
Well, yes you can if you wrap that method in a class dedicated the purpose. For reasons that I hope will become apparent, we’ll define an interface first.
… and a class that implements it:
Now you could create a Pythagoras class that can be told where to get its values.
In the constructor, we tell each Pythagoras object we create, how to get a pair of values. So we can use it like this:
What use is this? Well, it means we can invent other kinds of ValuePairSource. For example, a ShapeValuePairSource, which gets the values from a Shape object we set it up with.
(These are hypothetical classes for the purpose of the question)
So you might use it like this:
So without changing the Pythagoras class at all, we now have it reading the values from a shape object, rather than user input.
OK, it’s a bit of a contrived example, but it does answer the question “could I pass those methods to another method” — and this is the basis of things like Spring.
Note that some languages allow you to pass methods directly to other methods, without wrapping them in a class as we have here. This is called “functional programming”, and usually the “methods” are called “functions”.