在java 中,对String的+操作:
比如:String str1="a"; String str2=null; String str3=str1+str2;
此时操作str1和str2的时候,其实是在调用String的static修饰valueOf的方法:
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
所以结果就是"anull";
static修饰的方法是不能被复写的。为什么?
因为当一个方法被调用的时候,jvm会首先看这个方法是不是被static修饰的类方法,如果是,则会直接找到调用这个方法的对象所在类的这个方法。