Java类的“+”运算符
我有一个这样的课:
private static class Num { private int val; public Num(int val) { this.val = val; } }
是否可以使用“+” – 运算符添加到类的对象?
Num a = new Num(18); Num b = new Num(26); Num c = a + b;
不,你不能。 +
仅为数字,字符和String
重载,并且不允许定义任何其他重载。
有一种特殊情况,当你可以连接任何对象的字符串表示时 – 如果前两个操作数中有一个String
对象,则在所有其他对象上调用toString()
。
这是一个例子:
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
不,因为James Gosling如此说:
我遗漏了操作符重载作为一个相当个人的选择,因为我看到太多人在C ++中滥用它。
资料来源: http : //www.gotw.ca/publications/c_family_interview.htm
参考: 为什么Java不提供运算符重载?
不.Java不支持运算符重载(对于用户定义的类)。
java中没有运算符重载。 唯一支持对象的是通过“+”进行字符串连接。 如果您有一系列通过“+”连接的对象,并且其中至少有一个是String,则结果将内联到String创建。 例:
Integer a = 5; Object b = new Object(); String str = "Test" + a + b;
将被内联到
String str = new StringBuilder("Test").append(a).append(b).toString();
不,这是不可能的,因为Java不支持运算符重载 。