0

So, I created a simple class named Test, as follows:

import prog.utili.IntegerB;
//It's a custom class
class Test
{
   public static void main(String[] args)
   {
      IntegerB a = new IntegerB(1);
      IntegerB b = new IntegerB(2);
      IntegerB sum = a.plus(b);
      System.out.println(sum);
   }
}

I wanted to practise with inheritance so I created two custom classes. Fraction...

package prog.utili;
public class Fraction
{
   private int num;
   private int den;

   public Fraction(int x, int y)
   {
      [...]
   }

   public Fraction(int x)
   {
      this(x, 1);
   }

   public Fraction plus(Fraction f)
   {
      int n = this.num * f.den + this.den * f.num;
      int d = this.den * f.den;
      return new Fraction(n, d);
   }

   [...]
}

...and IntegerB:

package prog.utili;
public class IntegerB extends Fraction
{
   public IntegerB(int num)
   {
      super(num);
   }

   public IntegerB plus(IntegerB other)
   {
      return (IntegerB)this.plus(other);
   }
}

The problem is I keep getting the same error:

at prog.utili.IntegerB.plus(IntegerB.java:11)

I know I could simply solve the problem by just deleting the last method on IntegerB and replacing the 9th line of Test.java with

IntegerB sum = (IntegerB)a.plus(b)

but I absolutely want to do it using the inheritance rules over the "plus" method!

4

2 回答 2

1

要实现该方法plus(IntegerB),您调用plus(IntegerB),调用plus(IntegerB)等,等等,直到您收到 StackOverflowError。

为您的方法提供一个实际的实现:

return new IntegerB(this.getNum() + other.getNum());

或者

return new IntegerB(super.plus(other).getNum());

另请注意,将 Test.java 的最后一行替换为

IntegerB sum = (IntegerB)a.plus(b);

行不通,因为plus()in 中的方法Fraction不返回一个IntegerB,而是一个分数。因此,您将获得 ClassCastException。

于 2012-12-17T22:33:40.947 回答
0

这里的问题是它IntegerB.plus不会覆盖Fraction.plus,它会重载它。这是因为参数类型不同。因此,当IntegerB.plus调用时this.plus(other),它最终会调用自身,然后调用自身,然后调用自身,直到您获得 StackOverflow(从而将您发送到 stackoverflow : ))。

看起来你想打电话plus(Fraction)而不是plus(IntegerB). 为此,您可以明确地向上转型other

return plus((Fraction) other);

这个转换除了告诉编译器你想调用处理Fractions 的 plus 版本之外没有任何作用,即使你知道你有一个IntegerB.

但是,此方法不会返回 a IntegerB,而只是返回分母为 1 的 a 。如果结果Fraction的分母为 1,您可以重写plus以返回 an ,但这可能会导致不等于的IntegerB意外情况,因为 one 是一段时间另一个是. 或者,您可以尽可能返回对象。a.plus(b)b.plus(a)FractionIntegerBIntegerBFraction.plus

于 2012-12-18T02:41:26.677 回答