Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: add two objects

Tags:

java

object

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?

like image 464
Pavel Avatar asked Apr 20 '14 04:04

Pavel


People also ask

Can we add 2 objects in Java?

Is that possible? However, in Java there is no such thing as operator overloading. It would have to be written similar to i3 = i1. add(i2) (where add is a method that does the appropriate logic and creates the new object).

How do you sum two objects in Java?

By Using Integer.sum() Method The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator.

How do you add something in Java?

The add() method of Set in Java is used to add a specific element into a Set collection. The function adds the element only if the specified element is not already present in the set else the function return False if the element is already present in the Set.

How do you combine two lists of objects?

One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.


2 Answers

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);
like image 70
ApproachingDarknessFish Avatar answered Oct 02 '22 20:10

ApproachingDarknessFish


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.

like image 30
loknath Avatar answered Oct 02 '22 19:10

loknath