Java:一个对象构造函数将同一对象作为参数传递

6

我创建了一个名为Transaction的对象,并将其传递到ArrayQueue中。

以下是Transaction类的构造函数(还有相应的setter和getter):

public class Transaction {

    private int shares;
    private int price;

    public Transaction(int shares, int price) {
       this.shares = shares;
       this.price = price;
    }

    public Transaction(Object obj) {
       shares = obj.getShares();
       price = obj.getPrice();
    }
}

在第二个构造函数中,我想要一种情况,在其中可以传递一个已被出列的不同Transaction对象,并从该交易中获取信息并将其制作成新的交易或在将其放回队列之前进行可能的操作。但是当我编译它时,它不喜欢这样做。
将特定对象传递到自身对象的构造函数中是否是可接受的编程实践?或者说这是可能的吗?
5个回答

6

这被称为拷贝构造函数,你应该使用public Transaction(Transaction obj)代替Object,并提供getter方法:

public class Transaction {

    private int shares;
    private int price;

    public Transaction(int shares, int price) {
       this.shares = shares;
       this.price = price;
    }

    public Transaction(Transaction obj) {
       this(obj.getShares(), obj.getPrice()); // Call the constructor above with values from given Transaction
    }

    public int getShares(){
        return shares;
    }

    public int getPrice(){
        return price;
    }
}

5

您需要指定相同的类型:

public Transaction(Transaction obj) {
       shares = obj.getShares();
       price = obj.getPrice();
    }

只要您已经定义了getShares()和getPrice()函数。

为什么类型转换不起作用?这样我们甚至可以传递一个 Object 类型的参数。 - Ankit Rustagi
我刚试了两种方法,它们都可以用于我的客户端程序。谢谢! - Maggie S.
@AnkitRustagi 我想我会选择类型转换版本,正好符合那个点。再次感谢你。 - Maggie S.
1
当您使用对象并进行强制转换时,可能会意外地使用某些无法转换的内容 - 您的程序将在运行时失败。如果您明确地说“Transaction”,编译器将在实际执行代码之前告诉您正在做错事情,从而节省您的时间。 - Mariusz Jamro
我的回答大多是教学性的。现实生活中的代码应该首先检查接收到的对象是否为null,如果不是,则需要首先检查对象是否为Transaction的实例。只有在此之后才能安全地进行转换。除非你希望调用者捕获未经检查的异常。 - Akira
另外,如果您真的需要复制对象,请考虑实现java.lang.Cloneable接口并实现clone()方法。 - Akira

4
是的,这完全是可能的。
public Transaction(Transaction other){
    shares = other.shares;
    price = other.price;
}

您无需调用它们的 getter,因为隐私只适用于其他类。


2

是的,你可以这样做,但需要将参数强制转换。

public Transaction(Object obj) {
   Transaction myObj = (Transaction) obj; 
   shares = MyObj.getShares();
   price = MyObj.getPrice();
}

使用对象然后转换为Transaction没有任何好处,因为它只能与Transaction作为参数一起工作,并对所有其他类型抛出ClassCastException。Java是强类型的 - 让我们使用它! - Mariusz Jamro
是的,同意,但我只是想指出OP甚至可以传递一个Object类型的参数。 - Ankit Rustagi

0
例如,假设我们有一个名为Author的类,并创建了所有的getter方法, 要将另一个对象作为参数传递,我们使用以下语法。
public Author(ClassName variable){
    this(obj.getlength(), obj.getwidht())// height and width are the instance variable of the class.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接