主函数的Java输出
为什么输出是012。我不确定何时会调用方法WG,并且特定的过程是否相等主函数的Java输出,java,Java,为什么输出是012。我不确定何时会调用方法WG,并且特定的过程是否相等 class Wg { static int x = 0; int y; Wg() { y = x++; } public String toString() { return String.valueOf(y); } public static void main(String[] args) { String s = new Wg().toString(); s += ne
class Wg {
static int x = 0;
int y;
Wg() { y = x++; }
public String toString() {
return String.valueOf(y);
}
public static void main(String[] args) {
String s = new Wg().toString();
s += new Wg().toString();
s += new Wg().toString();
System.out.println(s);
} }
// Creates an Object of Type Wg and invokes the toString Method
// x = static i.e. shared between all classes (here: x = 0)
// x++;
// s = String.valueOf(y) = "0"
String s = new Wg().toString();
// Creates an Object of Type Wg and invokes the toString Method
// x = static i.e. shared between all classes (here: x = 1)
// x++;
// s = "0"+String.valueOf(y) = "01"
s += new Wg().toString();
// Creates an Object of Type Wg and invokes the toString Method
// x = static i.e. shared between all classes (here: x = 2)
// x++;
// s = "01"+String.valueOf(y) = "012"
s += new Wg().toString();
System.out.println(s);
所以
x
是静态的
,因此每次使用new Wg()
时,它都会增加x
,然后将结果分配给y
。问题是,你期望什么?每次我创建一个wg类型的对象并调用toString方法时,我都会调用wg方法(y=x++)。我说得对吗?我只是不确定wg类中的方法wg。wg(){y=x++}是wg类中的方法吗?以及何时调用此方法。。。。我不确定wg(){y=x++}是什么,以及如何使用它。当调用s+=new wg().toString()时,会发生两种不同的情况
a)创建一个新的Wg类对象并调用其构造函数Wg(){y=x++}
b)在新创建的对象上调用.toString()
方法,该方法返回y
作为字符串。y=x++
也可以这样写:x++代码>&y=x所以每当我创建一个新对象,我就会自动调用构造函数。我说的对吗?是的-在Java中,每个类都必须有一个构造函数-如果你自己不创建构造函数,编译器将创建一个空构造函数,即ClassName(){}
y = x;
x = x + 1;
String s = new Wg().toString(); // "0"
s += new Wg().toString(); // "0" + "1" == "01"
s += new Wg().toString(); // "01" + "2" == "012"