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;
No, you can't.
+
is overloaded only for numbers, chars andString
, 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:
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:
will be inlined to
No. Java does not support operator overloading (for user-defined classes).
No, because James Gosling said so:
Source: http://www.gotw.ca/publications/c_family_interview.htm
Reference: Why doesn't Java offer operator overloading?
No, it is not possible, as Java doesn't support operator overloading.