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

时间:2013-11-15 22:34:03

标签: java object constructor queue

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

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

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

5 个答案:

答案 0 :(得分:5)

您需要指定相同的类型:

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

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

答案 1 :(得分:5)

它被称为copy-constructor,您应该使用public Transaction(Transaction obj)代替Object并提供获取者:

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;
    }
}

答案 2 :(得分:4)

是的,这完全有可能。

public Transaction(Transaction other){
    shares = other.shares;
    price = other.price;
}

您无需致电他们的getter,因为隐私仅适用于其他类。

答案 3 :(得分:2)

是的,您可以这样做,但您必须输入强制转换参数

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

答案 4 :(得分:0)

例如,假设我们有一个创建所有吸气剂的Author类 传递另一个对象作为参数,我们使用以下语法

public Author(ClassName variable){
    this(obj.getlength(), obj.getwidht())// height and width are the instance variable of the class.
}