简体   繁体   English

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

[英]How to distinguish two instances of a class

I have two constructors of a class Transactions where they differ in the last argument where the first constructor takes a Label object and the second a Box object. 我有一个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;
}


 ...

}

Lets say I have created an object of class Transactions which is tr . 可以说我创建了一个Transactionstr的对象。 How can I distinguish which one is it? 我如何区分是哪一个? The one with the Label object or the one with the Box object? 一个带有Label对象或一个Box对象? Which constructor has been called? 哪个构造函数被调用?

If you need to distinguish that, both objects probably should not be of the same class. 如果您需要区分它们,则这两个对象可能不应属于同一类。

In your example, both classes could share a common superclass, or they should have a field of a special type, holding the common information. 在您的示例中,两个类可以共享一个公共超类,或者它们应该具有一个特殊类型的字段,其中包含公共信息。

You can easily check which one has just been called by checking if this.label == null . 您可以通过检查this.label == null来轻松检查刚刚调用过的this.label == null

You can also add a flag which would point which constructor has been called. 您还可以添加一个标志,该标志将指出已调用哪个构造函数。

Anyway. 无论如何。 If you are facing such a problem, you should definitely think out your code again. 如果您遇到此类问题,则绝对应该再次考虑您的代码。 Those constructors probably shouldn't construct objects of the same class. 这些构造函数可能不应该构造相同类的对象。 Maybe some inheritance, maybe some composition... 也许有些继承,也许有些组合...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM