提问人:Randolf Gabrielle Uy 提问时间:10/1/2023 最后编辑:Mark RotteveelRandolf Gabrielle Uy 更新时间:10/1/2023 访问量:48
在 Java 中传递对象直通方法 [duplicate]
Passing Object Through Method in Java [duplicate]
问:
我正在尝试让第二个对象通过我的方法,以便我可以从每个对象添加值。我正在尝试从“secondRational”对象访问分子属性和分母属性。
@Override
public RationalInterface add(RationalInterface secondRational) {
// How do I access the secondRational values within the child class Rational?
int numerator = this.num * secondRational.den + this.den * secondRational.num;
int denominator = this.den * secondRational.den;
this.num = numerator;
this.den = denominator;
return this;
} // end add
我收到的错误是 secondRational 的 den 符号未解析。
答:
-1赞
Manuna Mady
10/1/2023
#1
要从 secondRational 对象访问分子和分母属性,需要使用点表示法。例如,若要访问分子属性,可以使用以下代码:
int 分子 = secondRational.numerator; 若要访问分母属性,可以使用以下代码:
int 分母 = secondRational.denominator; 然后,可以在代码中使用这些变量来执行加法操作。
下面是代码的更新版本,它使用点表示法来访问 secondRational 值:
@Override
public RationalInterface add(RationalInterface secondRational) {
// Access the numerator and denominator values from the secondRational object
int numerator = this.num * secondRational.denominator + this.den * secondRational.numerator;
int denominator = this.den * secondRational.denominator;
// Update the numerator and denominator values for the current object
this.num = numerator;
this.den = denominator;
// Return the current object
return this;
} // end add
评论
0赞
Tim Roberts
10/2/2023
你为什么认为这会起作用? 并且是同一类型。如果对一个有效,那么它将对另一个有效。他们已经在使用点符号,这向我表明这个答案可能不是人类生成的。this
secondRational
den
评论
this.den
RationalInterface
den
den()