14

I have a class like this:

private static class Num {
    private int val;

    public Num(int val) {
        this.val = val;
    }
}

Is it possible to add to objects of the class by using the "+"-operator?

Num a = new Num(18);
Num b = new Num(26);
Num c = a + b;
multiholle
  • 3,050
  • 8
  • 41
  • 60

5 Answers5

15

No, you can't. + is overloaded only for numbers, chars and String, and you are not allowed to define any additional overloadings.

There is one special case, when you can concatenate any objects' string representation - if there is a String object in the first two operands, toString() is called on all other objects.

Here's an illustration:

int i = 0;
String s = "s";
Object o = new Object();
Foo foo = new Foo();

int r = i + i; // allowed
char c = 'c' + 'c'; // allowed
String s2 = s + s; // allowed
Object o2 = o + o; // NOT allowed
Foo foo = foo + foo; // NOT allowed
String s3 = s + o; // allowed, invokes o.toString() and uses StringBuilder
String s4 = s + o + foo; // allowed
String s5 = o + foo; // NOT allowed - there's no string operand
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • `String object somewhere` - not somewhere. It must be one of the first two operands, since `a+b+c` parses as `(a+b)+c` and the plus works only if at least one of the two operands is declared as a String. That's why `o+o+s` doesn't compile while the other two permutations do. – maaartinus May 04 '11 at 13:37
  • I thought it had to be the first operand. Nice to know it can be either of the first two. – will Oct 23 '14 at 15:04
14

No, because James Gosling said so:

I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.

Source: http://www.gotw.ca/publications/c_family_interview.htm

Reference: Why doesn't Java offer operator overloading?

Community
  • 1
  • 1
dertkw
  • 7,798
  • 5
  • 37
  • 45
6

No. Java does not support operator overloading (for user-defined classes).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
4

There is no operators overloading in java. The only thing which is supported for objects, is string concatenations via "+". If you have a sequences of objects joined via "+" and at least one of them is a String, then the result will be inlined to String creation. Example:

Integer a = 5;
Object b = new Object();

String str = "Test" + a + b;

will be inlined to

String str = new StringBuilder("Test").append(a).append(b).toString();
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
  • Good point, the `+` is a special case for strings, just to make life easier. The compiler replaces string concats with string builders – Java Drinker May 04 '11 at 13:10
3

No, it is not possible, as Java doesn't support operator overloading.

Riduidel
  • 22,052
  • 14
  • 85
  • 185