谁告诉我下,为什么这段代码的输出结果是这样
(最好能具体点)
——————————结果——————————
###
AAAZ
22
——————————代码——————————
public class Z {
static int i = 1;public static void main(String[] args) {
System.out.println("AAA" + new Z());
Z a = new Z();
Z b = new Z();
a.i++;
System.out.println("" + a.i + "" + b.i);
}public String toString() {
System.out.println("###");
return "Z";
}
}
——————————————————————
(最好能具体点)
——————————结果——————————
###
AAAZ
22
——————————代码——————————
public class Z {
static int i = 1;public static void main(String[] args) {
System.out.println("AAA" + new Z());
Z a = new Z();
Z b = new Z();
a.i++;
System.out.println("" + a.i + "" + b.i);
}public String toString() {
System.out.println("###");
return "Z";
}
}
——————————————————————
当运行System.out.println("AAA" + new Z());的时候,便执行toString方法
肯定先输出System.out.println("###");
然后返回Z和AAA一起输出。
22就不多说,"" + a.i + "" + b.i当字符串处理了。
你的toString()方法中真正用于输出的是return “Z”
之所以先输出### 是因为print之前拼接字符串的时候先调用了toString方法,在里面直接打印了“###”
自己的观点,希望对楼主有帮助
i是静态全局变量,只有单份内存拷贝,不是属于对象级别的,i的值为2.
String temp = new Z().toString(); //调用toString(),打印出“###”,并把"Z"赋值给temp
System.out.println("AAA" + temp); //打印出: “AAAZ”
public class Z {
static int i = 1;public static void main(String[] args) {
System.out.println("AAA" + new Z());
Z a = new Z();
Z b = new Z();
a.i++;
System.out.println("" + a.i + "" + b.i);
}public String toString() {
System.out.println("###");
return "Z";
}
}
代码里面有一个蓝色的地方,调用new z()的时候就自动调用了他的toString的方法,下面的输出应该简单把