在 Java 中传递对象直通方法 [duplicate]

Passing Object Through Method in Java [duplicate]

提问人:Randolf Gabrielle Uy 提问时间:10/1/2023 最后编辑:Mark RotteveelRandolf Gabrielle Uy 更新时间:10/1/2023 访问量:48

问:

我正在尝试让第二个对象通过我的方法,以便我可以从每个对象添加值。我正在尝试从“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 符号未解析。

enter image description here

Java 对象 方法 抽象

评论

4赞 seenukarthi 10/1/2023
我们的问题是什么?你有任何错误吗?
1赞 Abra 10/1/2023
你可能会认为有人会查看你发布的方法的代码,并告诉你如何修复它。我非常怀疑这会发生。我建议你阅读《如何提问》,并特别注意关于如何编写最小可重复示例的部分。顺便说一句,接口不能有属性
0赞 user207421 10/1/2023
这很简单。 不存在。this.den
0赞 user207421 10/1/2023
@TimRoberts 那会有什么不同?答:没有。
1赞 tquadrat 10/1/2023
的定义是什么?作为接口,它只能有方法和静态属性。 不是一个方法(那将是),静态是没有意义的。RationalInterfacedenden()

答:

-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
你为什么认为这会起作用? 并且是同一类型。如果对一个有效,那么它将对另一个有效。他们已经在使用点符号,这向我表明这个答案可能不是人类生成的。thissecondRationalden