How to add 2 objects in java

I'm new to Java and I couldn't find an answer to it because I don't even know how to look for it.

I want to define how two objects can be concatenated so that you get a new one, for example you can add String "a" and String "b" to get "ab".

I know it can be done in python by executing self.__add__(self, other)

. How can you do this in Java?

+3


source to share


3 answers


What you are looking for is called operator overloading. It exists in some languages, but it is not in Java.

The best you can do is define the add () method inside the class and then use it like this:



object1.add(object2);

      

I know it looks better with a + in between, but that will make compilation more difficult.

+2


source


Except being java.lang.String

treated as a special case 1 Java doesn't let you define behavior+

, , ++ Scala. , Java .

Your best bet is to build functions like add

& c. A call for use case here: see how for example the guys from Java using BigInteger

. Unfortunately, there is no way to prioritize your functions, so you have to use a lot of parentheses to tell the compiler how you want the expression to evaluate. For this reason, I don't use Java for any serious math applications, as implementing even a simple equation quickly becomes an unreadable mess 2 .




1 Which in some way does more harm than good: for example. consider 1 + 2 + "Hello" + 3 + 4

. This compile-time constant expression is a string type with a value 3Hello34

.

2 Note that C ++ was used to simulate the effects of gravitational lensing of a wormhole in the movie Interstellar. I encourage everyone to do this in a language that doesn't support operator overloading! See https://arxiv.org/pdf/1502.03808v1.pdf

+1


source


Java does not allow you to override operators. String

is a special case that allows this functionality.

What you can do is add a function add

:

public YourObject add(YourObject yourObject){
    return new YourObject(this.propertyToAdd + yourObject.propertyToAdd);
}

      

0


source







All Articles