为什么此题选B呢?。

  • 下列程序运行的结果是( )。
    class Counter {
    static int total;
    int number;
    Counter() {
      total++;
      number++;
    
    }
    }
    class Statistics {
    public static void main(String args[]) {
      Counter c = null;
      for (int i = 1; i < 3; i++)
          c = new Counter();
      System.out.println("number = " + c.number + " / total = " + c.total);
    
    }
    }
    A.number = 1 / total = 1
    B.number = 1 / total = 2
    C.number = 2 / total = 2
    D.number = 2 / total = 1

下面是我的思考,仅供参考:
是因为java对象的实例化特性和static关键的特性产生的这个结果。
首先,类的属性的默认值,int类型属性是0.(参考资料:https://blog.csdn.net/ITGGU/article/details/122433859
然后static关键字定义的类属性,在程序运行期间一直存在,所以在for循环,创建两个实例对象时,total++两次,就是从0变成2了。
然后类的非静态属性,创建一个对象,就新建一份对象属性,在创建对象c后,number++就只执行了一次,由默认的0变成1了。

img

static修饰的变量只有一份,无论创建多少个实例,操作的都是同一份static修饰变量

static 变量 又称了类变量 这个类无论创建多少个对象 这个变量都只有一份 所以 你循环2次 total 2
成员变量 对象独有 所以你创建这个类的对象的时候 每个队友都有自己的一个number 因此所有对象的number 都是 1