0

I writing a fraction calculator project.I'm trying to write the multiply method. And I need to downcast reference parameter FractionInterface to Fraction if I want to use it as SimpleFraction. Here's the FractionInterface:

public interface FractionInterface {
    public void setFraction(int num, int den);

    public void simplifyFraction();

    public double toDouble();

    public FractionInterface add(FractionInterface secondFraction);

    public FractionInterface subtract(FractionInterface secondFraction);

    public FractionInterface multiply(FractionInterface secondFraction);

    public FractionInterface divide(FractionInterface secondFraction);
}

Here's the method:

public FractionInterface multiply(FractionInterface secondFraction) {
    FractionInterface f = new Fraction(num,den);
    Fraction result = new Fraction((this.num * f.num),(this.den * f.den));//error:num cannot be resolved or is not a field
    return result;
}   // end multiply
Naman
  • 27,789
  • 26
  • 218
  • 353
Leslie Zhou
  • 361
  • 1
  • 3
  • 5
  • what do you expect `f.num` to be? The question needs more details over the implemented class and attributes shared in the code above. – Naman Mar 06 '17 at 12:15
  • You have no num property defined in your FractionInterface class. No den property either. You can't use properties that don't exist. – Chris Sharp Mar 06 '17 at 12:18
  • I just figured it out. it should be Fraction f = (Fraction) secondFraction; – Leslie Zhou Mar 06 '17 at 12:24
  • If that implementation is in `Fraction` class: The interface only call for `secondFraction` to be of type `FractionInterface`. Casting it without checks could fail. – Fildor Mar 06 '17 at 12:29

1 Answers1

0

error:num cannot be resolved or is not a field

f is a reference of type FractionInterface. You cannot access class fields through an interface reference; you need to downcast f to Fraction before you access its num and den fields.

Moving on, secondFraction nowhere is being used in the body of the function.

Anastasia
  • 712
  • 1
  • 5
  • 11