Java: add two objects

I was doing a project in Greenfoot , and I created an imaginary class of numbers. In my project, I found the need to add (or subtract or something else) two imaginary objects together, is there a way to add two such objects? Thus, it will 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 it possible?

+7
java object
source share
5 answers

There is no operator overload in Java.

For example, BigDecimal will be much more popular if you can write a + b instead of a.add(b) .

Method 1

 Imaginary i3 = i1.add(i2); 

Method:

 public static Imaginary add(Imaginary i2) { return new Imaginary(real + i2.real, imaginary + i2.imaginary); } 

Way 2 .

 Imaginary i3 = add(i1, i2) 

Method:

 public static Imaginary add(Imaginary i1, Imaginary i2) { return new Imaginary(i1.real + i2.real, i1.imaginary + i2.imaginary); } 

Overloading the operator would definitely make the design more complex than without it, and this could lead to a more complex compiler or slowdown of the JVM.

+3
source share

What you are describing is called β€œOperator Overloading,” and it cannot be done in Java (at least programmers like you and me, the developers are free to do this and have done so with the String class). Instead, you can create an add method and call this:

 Imaginary i3 = i1.add(i2); 
+8
source share

Try it like this.

 Imaginary i3 =new Imaginary(i1.real+i2.real,i1.imaginary+i2.imaginary); 

If you want to add an Object , you can create a method to add.

 public static Imaginary add(Imaginary i1,Imaginary i2) { return new Imaginary(i1.real+i2.real,i1.imaginary+i2.imaginary); } 

And create an object from this

 Imaginary i3 =add(i1,i2); 
+5
source share

In C ++ it is possible, but not in Java, define a function addImaginary(Imaginary, Imaginary) , which will add two Imaginarys and store them in the object, will be called by the method.

It will look like this:

 i3.addImaginary(i1, i2) 

But you decide how you define the function, you can also do this like this:

 i3=i1.add(i2); 
+3
source share

Java does not support user-defined operator overloading. But you can make a method in the Imaginary class:

 public static Imaginary add(Imaginary other) { return new Imaginary(real + other.real, imaginary + other.imaginary); } 

so you can call it the following:

 Imaginary i3 = i1.add(i2); 
+3
source share

All Articles