Java输出的主要功能

时间:2015-09-24 23:50:04

标签: java

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);
} }

为什么输出为012.我不确定何时调用方法WG和具体的程序

2 个答案:

答案 0 :(得分:0)

// 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);

答案 1 :(得分:0)

y = x++等于

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"