
Returning an object
I am working on a project that does different operations on fractions. I have created fraction objects called f1 and f2, with numerator and denominator as their parameters.
My teacher has instructed us to make it work with this in the main method:
Code:
fraction f1 = new fraction(3,4);
fraction f2 = new fraction(1,8);
fraction result = f1.plus(f2);
Now assuming that everything in the plus method works correctly, how would I return a fraction?
In the fraction class I have:
Code:
public fraction plus(fraction f)
but I don't know how to return an object.
Would I just return the two parameters like:
Code:
return (numerator,denominator);
?
Sorry if my terminology or explanation is poor, but I'm in my first semester of java.

If you have an object in the function, like this:
Code:
public fraction plus(fraction f) {
this.value += f.value;
}
Then you can just return this.
If you do something like this...
Code:
public fraction plus(fraction f) {
fraction n = new fraction(this.value + f.value);
}
Then you'll want to return n instead.
Personally I'd go with the first method, but it all depends what you have so far. I'm just using .value as a placeholder for whatever your data already is, since I can't see your actual source.

Thanks Zack! I used the second method and all is working now.

Try to understand how it works.