【问题标题】:how does this java code counts the number of things?这个java代码如何计算事物的数量?
【发布时间】:2020-11-05 23:45:47
【问题描述】:

愚蠢的问题,但有人可以向我解释为什么下面的代码计算事物对象的数量吗?我不明白为什么定义的计数方法会计算对象的数量?迭代什么时候开始?任何有关澄清的帮助将不胜感激

class Thing {
public String name;

    public static int count = 0;
    public Thing() {

        id = count;
        count++;
    }
    public void showName() {
        System.out.println("Object ID: " + id + ", " + description + ": " + name);
    }
}

public class Java_Static {
public static void main(String[] args) {

    
    // using count method
    System.out.println("Before creating objects, count is: " + Thing.count);

    // using variable
    Thing thing1 = new Thing();
    Thing thing2 = new Thing();

    thing1.name = "Abid";
    thing2.name = "Ruksaar";

    thing1.showName();
    thing2.showName();

    System.out.println("After creating objects, count is: " + Thing.count);

    


    

}

}

【问题讨论】:

  • 没有count方法,只是一个字段,基本上是一个在构造函数中递增的全局变量。
  • 请注意,使用可修改的类字段(而不是实例字段)被认为是代码异味。相反,您可以使用工厂模式,例如,工厂保持计数。
  • 每创建一个Thing对象,静态变量Thing.count就会增加。

标签: java class object count


【解决方案1】:

整数countThing 类的静态字段。这意味着各个Thing 对象没有自己的计数,只有Thing 类存储count 的值。因此,每当更新 count 时,就像在 Thing 构造函数中一样,都会更新相同的变量。这允许count 变量存储Thing 对象的数量,因为每次构造Thing 时它都会递增1。

【讨论】:

  • 谢谢你,这对我的理解有帮助,我想这需要一些时间来理解:)
【解决方案2】:

Thing() 方法称为构造函数,每次都会触发它,并且对象是从该类生成的。

当一个方法与它所在的类同名时,它被识别为构造函数。

因此,每次创建一个对象时,它都会运行“Thing()”构造函数,该构造函数具有“count++”,它会增加计数变量。

【讨论】:

  • 谢谢!所以每次我创建一个 Thing 类型的新对象时,都会运行 Thing 构造函数,并且因为 Thing 构造函数进行计数,所以每次创建 Thing 对象时,计数都会增加? ——这就是原因吗?还是我的知识有差距?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2023-01-26
相关资源
最近更新 更多