Using a method to add two classes and produce a third
Hey community i was assigned a home work asking me to create a method to add two instances of a fraction object and have the output be a new instance .
here is the prompt i was given
"Provide a method add that receives a second fraction as an argument, and returns a new fraction which is the sum of fractions. Example: Fraction r3 = r1.add( r2 );"
could someone please explain how this is done ?
Re: Using a method to add two classes and produce a third
Do you know how to create an instance of a class? Hint: Use the new statement.
Take values from the current class and the passed argument, create an instance of the class with those values and return it.
Re: Using a method to add two classes and produce a third
Thanks for the response Norm , i know how to create the instances im just having trouble understanding how my method is taking the values from both classes and producing a new instance with the new values .
Re: Using a method to add two classes and produce a third
Take it one step at a time.
Where are the values located?
One is local,
the other is in the passed object. You'll need to call a method to get it.
How are the two values added together to get a result?
How do you use that resultant value to create the new instance?
Re: Using a method to add two classes and produce a third
What is my method returning can it return a new instance of the class if so what is the syntax ? public ___ add(Fraction a)
Re: Using a method to add two classes and produce a third
Look at how the call is made:
Fraction r3 = r1.add( r2 );"
What data type is r3?
That is what the add method must return.
Re: Using a method to add two classes and produce a third
Norm you are BRILLIANT thankyou for all of your help here is the code do you have any further pointers ?
public Fraction add(Fraction f)
{
int n,d;
if(denominator == f.getDenominator())
{
n = numerator + f.getNumerator();
d = denominator ;
return new Fraction (n,d);
}
else {
d = denominator*f.getDenominator() ;
n = ((numerator*f.getDenominator())+(f.getNumerator()* denominator));
return new Fraction(n,d);
}