主函数的Java输出

主函数的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

为什么输出是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 += 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=xClassName(){}
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"