quot;+quot; operator for Java-classes(“+Java 类的运算符)
问题描述
我有这样的课:
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;
推荐答案
不,你不能.+
仅对数字、字符和 String
进行重载,并且不允许定义任何额外的重载.
No, you can't. +
is overloaded only for numbers, chars and String
, and you are not allowed to define any additional overloadings.
有一种特殊情况,当您可以连接任何对象的字符串表示时 - 如果前两个操作数中有 String
对象,则调用 toString()
在所有其他对象上.
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.
这是一个插图:
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 类的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“+"Java 类的运算符


基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01