创建了多少个对象 - Java

时间:2015-11-03 17:49:58

标签: java object

我正在讨论在以下示例中创建了多少个对象。我相信应该有5但我不太确定。

class Test {
   int a;  int b;
   Test(){
   }
   Test(int a_, int b_){
      a=a_; b=b_;
   }
   Test(Test r){
      a=r.a; b=r.b;
   }
   void povecaj() {
      a++; b++;
   }
   Test dodaj(Test r)
      Test t = new Test(a+r.a, b+r.b);
      return t;
   }
}

// ...
Test t1 = new Test();
Test t2 = new Test(1, 2);
t1.povecaj();
Test t3 = new Test(t2);
t1 = t1.dodaj(t3);
t2 = t3;

2 个答案:

答案 0 :(得分:3)

实际上,您使用小程序创建了4个Test类型的对象。在这个简单的程序中,您可以轻松计算new关键字的出现次数。

您可以通过调试代码...或维护静态计数变量来检查:

class Test {
    static int count; // used for counting instance creations

    int a;
    int b;

    Test() {
        count += 1; // new instance created => increment count
    }

    Test(int a_, int b_) {
        this(); // Absolutely needed to have the counter incremented!
        a = a_;
        b = b_;
    }

    Test(Test r) {
        this(); // Absolutely needed to have the counter incremented!
        a = r.a;
        b = r.b;
    }

    void povecaj() {
        a++;
        b++;
    }

    Test dodaj(Test r) {
        Test t = new Test(a + r.a, b + r.b);
        return t;
    }

    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test(1, 2);
        t1.povecaj();
        Test t3 = new Test(t2);
        t1 = t1.dodaj(t3);
        t2 = t3;
        System.out.println(count);
    }
}

打印

  

4

答案 1 :(得分:1)

可以创建新对象explicitly or implicitly

使用字符串文字,字符串连接,自动装箱可以进行隐式创建。在Java 8中,它也可以使用方法引用表达式和lambda表达式。

您显示的代码不包含任何隐式对象创建。它也不会调用任何可能创建对象的外部代码。

因此,通过调用new,可以显式创建此代码创建的所有对象。 此代码调用new四次,因此会创建四个对象。

Test t1 = new Test();      // One 
Test t2 = new Test(1, 2);  // Two
t1.povecaj();
Test t3 = new Test(t2);    // Three
t1 = t1.dodaj(t3);         // Four, in the method implementation