[英]Java interfaces and downcasting
I have a Fraction
class which implements an interface named FractionInterface
. 我有一个Fraction
类,该类实现了一个名为FractionInterface
的接口。 In FractionInterface
I have specified a method FractionInterface add(FractionInterface secondFraction);
在FractionInterface
我指定了一个FractionInterface add(FractionInterface secondFraction);
方法FractionInterface add(FractionInterface secondFraction);
. 。 I am having trouble implementing this method in my Fraction
class. 我在Fraction
类中无法实现此方法。
public class Fraction implements FractionInterface
{private int num; // Numerator
private int den; // Denominator
public int getNum()
{
return this.num;
} // end getNum
public int getDen()
{
return this.den;
} // end getDen
public FractionInterface add(FractionInterface secondFraction)
{
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
}
}
I get an error saying "Type mismatch: cannot convert from int to FractionInterface.", I was given a hint to downcast the parameter secondFraction from FractionInterface to Fraction but i'm not sure how to do that. 我收到一条错误消息:“类型不匹配:无法从int转换为FractionInterface。”,我得到了将参数secondFraction从FractionInterface转换为Fraction的提示,但我不确定该怎么做。 Could someone explain what I am doing wrong? 有人可以解释我在做什么错吗?
What do you expect this to do? 您期望这做什么?
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
The right side is a number, the left side is an object. 右侧是数字,左侧是对象。 The compiler has no way to know how to convert a number into a Fraction
object. 编译器无法知道如何将数字转换为Fraction
对象。
You need a constructor in your Fraction
class that accepts a numerator and denominator: 在Fraction
类中需要一个接受分子和分母的构造函数:
public Fraction(int numerator, int denominator) {
num = numerator;
den = denominator;
}
and then do this 然后做
FractionInterface result = new Fraction(THENUMERATOR, THEDEMONIMATOR);
which I think, for you, is 我认为对您来说
FractionInterface result = new Fraction(
(num*secondFraction.getDen()+secondFraction.getNum()*den),
(den*secondFraction.getDen());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.