2

I need to program a java-class "Fraction".

This class should be able to understand the basic arithmetic operations like +, -, *, /. I found lots of "Fraction" classes and understand them, but all use methods like "f1.add(f2);" (f1, f2 are objects of Fraction, for Example:

f1 = new Fraction(1,5);
f2 = new Fraction(2,5);

What I need is a direct manipulation like the manipulation of integers, for example:

**f1 = f1 + f2;**

instead of

f1.add(f2);
Paolof76
  • 889
  • 1
  • 9
  • 23

4 Answers4

6

You can't: java doesn't allow overloading operators.

eternay
  • 3,754
  • 2
  • 29
  • 27
  • Thanks for that answer. So I will have to try out a new programming language :/ Someone has an advice for me? C#, C++? Perhaps PHP? – user2452336 Jun 04 '13 at 15:38
1

This is not possible in standard Java.

As you have asked explicitly in a comment: I suggest Scala (in contrast to Groovy), because it's type-safe (among many other advantages), and it is a JVM language as well:

class Fraction(val n: Int, val d: Int) {
  override def toString = s"$n/$d"

  def +(that: Fraction) = new Fraction(this.n + that.n, this.d)
}

object FractionDemo extends App {
  val f1 = new Fraction(1, 4)
  val f2 = new Fraction(2, 4)
  val f3 = f1 + f2
  println(s"$f1 + $f2 = $f3")
}

and the output is

1/4 + 2/4 = 3/4

I know that + is not implemented correctly, this is just a small example.

If you are interested in a numerical library for Scala, have a look at spire, it already has a Fractional class.

Beryllium
  • 12,808
  • 10
  • 56
  • 86
0

As eternay said, Java doesn't support operator overloading. You could look at Groovy.It is a Java-like JVM-based language which does support operator overloading.

stinepike
  • 54,068
  • 14
  • 92
  • 112
0

If you're interested in a language based in JVM that support operator overloading you can try Groovy. See here some discussion: Operator overloading in Java

Community
  • 1
  • 1
Paolof76
  • 889
  • 1
  • 9
  • 23