给大家看一个比较有趣的代码:
package com.crazyit;
public class Student {
public static void main(String[] args) {
Object he = new Student();
String str = "hello";
str += he;
System.out.println(str);
}
}
运行结果如下:
但是如果改为这样:
package com.crazyit;
public class Student {
public static void main(String[] args) {
Object he = new Student();
String str = "hello";
he += str;
System.out.println(he);
}
}
运行显示如下:
为什么会出现这样的情况,
因为对于第一个程序,+=左边的变量类型是String,所以he将自动转换为String(就是使用它的toString()返回值),Object是String的父类
而对第2个程序,+=左边的变量类型不是String类型,所以产生错误。
下面再看一个程序:
package com.crazyit;
public class Student {
public static void main(String[] args) {
Object he = new Student();
String str = "hello";
he = he + str;
System.out.println(he);
}
}
运行结果如下:
因为此时系统自动将he转换为String类型后与str连接进行运算。