Reputation: 111
I am having trouble in figuring out why the line of code that says Fraction Interface f = etc... does not work. The problem is in .denominator and .numerator. It seems that I am not supposed to implement get methods. So, how I am going to access the denominator and the numerator of aFraction?
Below you also see the methods in the interface. Many thanks.
public class Fraction implements FractionInterface, Comparable<Fraction> {
private int numerator;
private int denominator;
public Fraction()
{
numerator = 0;
denominator = 1;
}
public Fraction(int num, int den)
{
numerator = num;
denominator = den;
}
public FractionInterface add(FractionInterface aFraction)
{
// return a new Fraction object
// a/b + c/d is (ad + cb)/(bd)
// implement this method!
// WHY .denominator and .numerator do work ?
FractionInterface f = new Fraction((numerator*aFraction.denominator))
+ (aFraction.numerator * denominator) , (denominator *aFraction.this.denominator));
return f
}
}
public interface FractionInterface {
/** Task: Sets a fraction to a given value.
public void setFraction(int num, int den);
public double toDouble();
public FractionInterface add(FractionInterface aFraction);
public FractionInterface subtract(FractionInterface aFraction);
public FractionInterface multiply(FractionInterface aFraction);
public FractionInterface divide(FractionInterface aFraction);
public FractionInterface getReciprocal();
}
Upvotes: 0
Views: 975
Reputation: 494
Try creating a method getNumerator()
that calls the numerator
variable from this
. So when you call this.getNumerator()
, it calls the variable numerator
associated with the given fraction. This is especially useful when dealing with more than one fraction in a method. Creating a getNumerator()
method is as simple as
public int getNumerator(){
return numerator;
}
since it just needs to grab the member variables(you don't need to initialize anything). Do the same for the denominator. Now you can call both as foo.getNumerator()
.
Upvotes: 0
Reputation: 285403
Give your interface getter method signatures for the numerator and denominator,
public int getNumerator();
public int getDenominator();
implement these in your concrete class, and then call these methods when you need a numerator or denominator.
Upvotes: 1