Pavel
Pavel

Reputation: 1103

Java: add two objects

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?

Upvotes: 13

Views: 33659

Answers (5)

loknath
loknath

Reputation: 1372

Java has no operator overloading.

For example, BigDecimal would be a lot more popular if you could write a + b instead of a.add(b).

Way 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);
}

Operator overloading would have definitely made design more complex than without it, and it might have led to more complex compiler or slows the JVM.

Upvotes: 6

Akash Thakare
Akash Thakare

Reputation: 22972

Try Like this.

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

If you want to add Object you can create method for addition.

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

And create Object from this

Imaginary i3 =add(i1,i2);

Upvotes: 6

Christian Tapia
Christian Tapia

Reputation: 34146

Java doesn't support user-defined operator overloading. But you can make a method in your Imaginary class:

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

so, you can call it like:

Imaginary i3 = i1.add(i2);

Upvotes: 4

Ved
Ved

Reputation: 369

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

It will look like:

i3.addImaginary(i1, i2)

But it is up to you how you define the function, it can also be done as:

i3=i1.add(i2);

Upvotes: 4

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

What you are describing is called "Operator overloading" and it cannot be accomplished in Java (at least by programmers such as you and me; the developers have free reign to do this and did so with the String class). Instead, you can create an add method and call that:

Imaginary i3 = i1.add(i2);

Upvotes: 9

Related Questions