I was making a project in Greenfoot and I made an imaginary number class. In my project I found a need to add (or subtract, or whatever) two imaginary objects together, is there a way to add two objects like that? So this is how it would look in a perfect world:
Imaginary i1 = new Imaginary(1.7,3.14);
Imaginary i2 = new Imaginary(5.3,9.1);
//the class Imaginary has parameters (double real, double imaginary)
Imaginary i3 = i1+i2;
Is that possible?
Best How To :
no operator overloading
.For example, BigDecimal would be a lot more popular if you could write a + b instead of a.add(b).
method should be
public static Imaginary add(Imaginary i2)
return new Imaginary(real+i2.real,imaginary+i2.imaginary);
public static Imaginary add(Imaginary i1,Imaginary i2)
return new Imaginary(i1.real+i2.real,i1.imaginary+i2.imaginary);
Operator overloading would have definitely made design more complex than without it, and it might have lead to more complex compiler or slows the JVM .