“+” Java类的运算符 [英] "+" operator for Java-classes
本文介绍了“+” Java类的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的类:
私人静态类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
重载,并且不允许定义任何额外的重载。 p>
有一个特殊情况,当你可以连接任何对象的字符串表示 - 如果在 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; //不允许
Foo foo = foo + foo; //不允许
String s3 = s + o; //允许,调用o.toString()并使用StringBuilder
String s4 = s + o + foo; // allowed
String s5 = o + foo; //不允许 - 没有字符串操作数
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 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
这篇关于“+” Java类的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文