用类调用实例方法

时间:2015-03-04 00:50:34

标签: java instance-variables

我在网上找到了以下代码:

class TestA
 {
 public static void main(String[] args) {
 A a1 = new A();
 A a2 = new A(5);
 a2.setValue(10);
 System.out.println(a1.getValue() + " " +a2.getValue() + " " + A.getChanges());
 }
}

我理解a1.getValuea2.getValue因为它们是调用实例方法的对象引用。如果我按照下面的TestA方法,我会得到正确的前两个答案" 0 10"。但我不理解A.getChanges(),因为它是类本身调用实例方法的。为什么这样做?另外,如果我遵循changes变量,我认为这应该返回2,但是当我用Java测试它时,我得到了返回" 0 10 3"。谁能解释一下呢?

一个名为A的课程:

class A
 {
 private static int changes = 0;
 private int value;
  public A() {
   this(0);
  }
  public A(int value) {
   setValue(value);
  }
  public int getValue() {
   return value;
  }
  public void setValue(int value) {
   this.value = value;
   changes++;
  }
  public static int getChanges() {
   return changes;
  }
}

0 个答案:

没有答案