测试代码:
String String = "abc";
System.out.println(String);
//输出为 abc
char[] CharArray = new char[]{'a','b','c'};
System.out.println(CharArray);
//输出为 abc
int[] IntArray = new int[]{1,2,3};
System.out.println(IntArray);
//输出为 [I@28a418fc
char[] CharArray2 = new char[]{'d','e','f'};
System.out.println("a"+CharArray2);
//输出为 a[C@5305068a
//"a"+CharArray2 先进行字符串的拼接,调用参数为String类型的println()重载方法
//接下来调用String.valueOf(Object object),打印该对象的哈希码
可以发现,有的输出abc是我们想要的结果;有的却是a[C@5305068a 这又是什么呢?
概述:
概述:println()方法内部调用String.valueOf()方法 ,后者内部根据参数的不同调用String()方法或者toString()方法。从而产生差异。
原理解析:
println重载方法
valueOf()的重载方法
println()方法: 参数为数字型、char数组、字符串
public void println(double x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
public void println(char[] x) {
if (getClass() == PrintStream.class) {
writeln(x);
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
public void println(String x) {
if (getClass() == PrintStream.class) {
writeln(String.valueOf(x));
} else {
synchronized (this) {
print(x);
newLine();
}
}
}
以上各种情况输出的是:字符串
println()方法:参数为Object类型
public void println(Object x) {
String s = String.valueOf(x);
if (getClass() == PrintStream.class) {
// need to apply String.valueOf again since first invocation
// might return null
writeln(String.valueOf(s));
} else {
synchronized (this) {
print(s);
newLine();
}
}
}
println方法接收的x对象传给了String.valueOf()方法。
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
调用了obj.toString()方法。如果java对象没有对父类Object的toString()方法重写,那么就会调用父类的obj.toString()方法
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
输出的是:getClass().getName() + "@" + Integer.toHexString(hashCode())
总结:
如果没有重写toString()方法,会调用默认的Object 的toString()方法,
字符串:输出字符串
数字:转为字符串输出
对象:hash码(即 getClass().getName() + "@" + Integer.toHexString(hashCode()))
2.重写toString()方法,覆盖父类方法,可以自定义输出