class Person {
private int id;
public static int total = 0;
public Person() {
 total++;
 id = total;
}
}
class OtherClass {
public static void main(String args[]) {
Person.total = 100;
System.out.println(Person.total);
Person c = new Person();
System.out.println(Person.total);
}
}
结果为什么先是100 后是101呢~~看不懂

解决方案 »

  1.   

    class Person {
    private int id;
    public static int total = 0;
    public Person() {
     total++;
     id = total;
    }
    }
    class OtherClass {
    public static void main(String args[]) {
    Person.total = 100;//重新给total赋值,值就是100
    System.out.println(Person.total);//这个时候,就是上面的值100
    Person c = new Person();//重新给total赋值,由于total在上面已经是100了,在total++后,total就是101了。因为total是static的,所以,保留了上次赋的值100。
    System.out.println(Person.total);//所以是101
    }
    }
      

  2.   

    public static int total = 0;
       total类型为static;Person.total = 100;
    System.out.println(Person.total);
       这两句打印结果是100
       因为total类型为static,其值保持为100不清零;
     
    Person c = new Person();
      在初始化过程中,total++,即101System.out.println(Person.total);
      打印结果是101
      

  3.   

    total是一个静态变量,也叫类变量,就是无论你new了多少个Person的实例,total始终只有一个,而且只要有Person或者Person的实例改变过它,它的值就会改变,而且会保持着最近的修改的值,直到继续被修改。于是,在执行Person.total = 100;,这时输出的自然是100了;
    在执行Person c = new Person();后,由于Person的构造方法中,total自增了1,这时total也主变成101了,所以就输出101了^_^
      

  4.   

    有几个问题要先明白.
    1,total是静态的.
    2,构造方法因为total是静态的,所以可以直接赋值Person.total = 100;,total的值就成为100,所以打印也来也就是100
    这个应该好理解.
    然后Person c = new Person();
    创建对象的时候,调用了构造方法,"total++;"代码被执行.还是因为total是静态的,且已被赋值100,所以total++;执行后,total为101
    大概就是这个样子.
      

  5.   

    class Person {
    private int id;
    public static int total = 0;
    public Person() {
     total++;
     id = total;
    }
    }
    class OtherClass {
    public static void main(String args[]) {
    Person.total = 100;//对上边的类中的静态变量副职,该类未被构造
    System.out.println(Person.total);//输出100,刚给的值
    Person c = new Person();//经过构造对100+1
    System.out.println(Person.total);//输出累加过的  为101
    }
    }