Java方法传参问题:无法访问传入对象的属性
解决Rational类add方法中无法访问接口对象属性的问题
你遇到的错误核心原因是:RationalInterface作为接口,并没有定义num和den这些字段,而且你的Rational类里的num、den应该是私有属性(否则也不会通过接口访问出错),外部无法直接通过接口引用访问这些私有字段。
解决方案步骤
- 在
RationalInterface中添加获取分子、分母的抽象方法 - 在
Rational类中实现这两个getter方法 - 修改
add方法,通过getter方法获取第二个对象的分子和分母
修改后的代码示例
首先更新接口定义,添加getter方法:
public interface RationalInterface { RationalInterface add(RationalInterface secondRational); // 添加获取分子和分母的抽象方法 int getNumerator(); int getDenominator(); }
然后在Rational类中实现接口方法并修改add逻辑:
public class Rational implements RationalInterface { private int num; private int den; // 构造方法示例 public Rational(int num, int den) { this.num = num; this.den = den; } // 实现接口的getter方法,暴露私有属性的访问入口 @Override public int getNumerator() { return num; } @Override public int getDenominator() { return den; } @Override public RationalInterface add(RationalInterface secondRational) { // 通过getter方法安全获取第二个对象的分子和分母 int secondNum = secondRational.getNumerator(); int secondDen = secondRational.getDenominator(); int newNum = this.num * secondDen + this.den * secondNum; int newDen = this.den * secondDen; // 建议返回新对象,避免修改原对象(符合数学运算的无副作用设计) return new Rational(newNum, newDen); // 如果一定要修改调用add方法的原对象,可替换为以下代码: // this.num = newNum; // this.den = newDen; // return this; } }
内容的提问来源于stack exchange,提问作者Randolf Gabrielle Uy
相关产品推荐
相关产品推荐

