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

Mag*_* S. 6 java queue constructor object

我创建了一个名为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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在第二个构造函数中,我想要一个场景,我可以在其中传递一个已经出列(ed)的不同Transaction对象,并从该事务中获取信息并将其转换为新事务或在我将其放回之前对其进行操作进入队列.但是当我编译它不喜欢这个.

这种可接受的编程习惯是将特定对象传递给它自己的对象的构造函数吗?或者这甚至可能吗?

Aki*_*ira 5

您需要指定相同的类型:

public Transaction(Transaction obj) {
       shares = obj.getShares();
       price = obj.getPrice();
    }
Run Code Online (Sandbox Code Playgroud)

前提是已定义getShares()和getPrice()。


Mar*_*mro 5

它称为copy-constructor,您应该使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)