问题
I have a doubt regarding operator overloading in Java. I know that Java does not support operator overloading but then what is the "+" operator doing in below valid Java program:
import java.util.*;
import java.lang.*;
import java.io.*;
class OperatorOverloadingTest
{
public static void main (String[] args) throws java.lang.Exception
{
String str1 = "Operator ";
String str2 = "overloading";
String str3 = str1+str2;
System.out.println(str3);
}
}
Stdout:
Operator overloading
回答1:
This operator is not "overloaded", it is pre-defined operator, called String Concatenation Operator.
15.18.1 String Concatenation Operator
+
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time. The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
In other words, when Java sees
String res = stringObj + someObj;
it replaces the expression with code that constructs the resulting string by concatenating an existing string value with someObj.toString()
.
来源:https://stackoverflow.com/questions/29084340/java-operator-overloading-and-operator-for-string