【问题标题】:How to make number automatically in the Constructor java如何在构造函数java中自动生成数字
【发布时间】:2016-05-28 08:53:02
【问题描述】:

我有两个构造函数:

private int num ;
private Room room ;
private boolean status;
private E_types type ;

1-:部分构造函数:

Instrument(int num)
Partial Constructor ~ use for initial key fields

2-:完整构造函数:

Instrument(Room room, boolean status, E_Types type)
Full Constructor ~ use for initial all fields instruments should be numbered automatically

这是什么自动编号?

谢谢:)

【问题讨论】:

  • 你从哪里得到这个代码?
  • “这个自动编号是什么?” 你得问问给你任务的人,他们的意思是什么。我们可以猜测,但他们会知道
  • 我猜他们的意思是“自动编号”,有默认值或初始值。

标签: java oop constructor static


【解决方案1】:

您需要类中的static 变量,该变量会随着每个 Instrument 的创建而自动增加。简单解释一下static 的含义:它是一个类的所有实例的变量。让它分配给num

public class Instrument {
    private static int id = 0; // representing ID
    private int num = 0;
    private Room room ;
    private boolean status;
    private E_types type ;

    public Instrument(Room room, boolean status, E_Types type) {
        Instrument.id++;
        this.num = Instrument.id;
        this.room = room;
        this.status = status;
        this.type = type;
    }

    public static int getID() {
        return Instrument.id;
    }

    public int getNum() {
       return this.num;
    }
}

让我们用一个例子来试试。让我们在上面的构造函数的基础上创建 4 个 Instruments 并调用 getter 和返回最大 ID 的静态方法。

Instrument a = new Instrument(...);
Instrument b = new Instrument(...);
Instrument c = new Instrument(...);
Instrument d = new Instrument(...);

System.out.println(c.getNum()); // prints 3, num of "c" instrument
System.out.println(Instrument.getID()); // prints 4 (total of instruments)

【讨论】:

  • 谢谢,我试过了,效果很好!那么,当我们需要共享给所有对象的东西时,我们需要使用静态吗?对吗?
猜你喜欢
  • 2019-09-25
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 2016-12-07
  • 2011-08-21
  • 2014-02-21
  • 1970-01-01
  • 2011-03-29
相关资源
最近更新 更多