如何区分一个类的两个实例

yay*_*zis 1 java constructor

我有一个类的两个构造函数Transactions,它们在最后一个参数中有所不同,其中第一个构造函数接受一个Label对象,第二个构造函数接受一个Box对象.

public class Transactions {
    private String date;
    private String kind;
    private int employee;
    private Label label;
    private Box box;

public Transactions(String date, String kind, int employee, Box box) {
    this.date = date;
    this.kind = kind;
    this.employee = employee;
    this.box = box;
}

public Transactions(String date, String kind, int employee, Label label) {
    this.date = date;
    this.kind = kind;
    this.employee = employee;
    this.label = label;
}


 ...

}
Run Code Online (Sandbox Code Playgroud)

比方说,我创建类的对象Transactionstr.我该如何区分它是哪一个?一个与Label对象或一个与Box对象?哪个构造函数被调用?

JF *_*ier 5

如果你需要区分它,两个对象可能不应该是同一个类.

在您的示例中,两个类可以共享一个公共超类,或者它们应该具有一个特殊类型的字段,并保存公共信息.