Java Copy构造函数不复制值

时间:2012-10-09 03:48:13

标签: java copy-constructor

我编写了一个模拟股票的类:

public Stock(String ticker, int shares, float purchasePrice) throws IllegalArgumentException
{
    if(ticker == null || ticker == "" ||
        shares <= 0 || purchasePrice <= 0)
        throw new IllegalArgumentException(Messages.enterAppropriateValues());

    this.ticker = ticker;
    this.shares = shares;
    this.purchasePrice = purchasePrice;
    latestPrice = purchasePrice;
    updatePercentGain();
}

复制构造函数如下所示:

public Stock(Stock other) throws IllegalArgumentException
{
    this(other.ticker, other.shares, other.purchasePrice);
}

以下是我用来测试它的命令:

    Stock bac = new Stock("BAC", 100, 42.22f);
    System.out.println(bac);

    bac.setLatestPrice(43.35f);
    System.out.println(bac);

    Stock bacCopy = new Stock(bac);
    System.out.println(bacCopy);

输出是:

    BAC 100 42.22 42.22 0.00%
    BAC 100 42.22 43.35 2.68%
    BAC 100 42.22 42.22 0.00%

出于某种原因,代表百分比增益的最后一个值是不是要复制?

这是百分比增益法btw:

public void updatePercentGain()
{
    percentGain = ((latestPrice - purchasePrice) / purchasePrice) * 100;
}

我哪里错了?

2 个答案:

答案 0 :(得分:3)

当您的Stock构造函数运行时,它会将latestPrice初始化,并将purchasePrice传入构造函数。由于这些值相同,增益百分比为0.00%。

如果您还希望复制复制构造函数中的当前latestPrice,您也必须这样做:

public Stock(Stock other) throws IllegalArgumentException
{
    this(other.ticker, other.shares, other.purchasePrice);
    this.latestPrice = other.latestPrice;
    updatePercentGain();
}

答案 1 :(得分:2)

在你的实际构造函数(不是你的复制构造函数)中,你没有复制到latestPrice,你只是将它设置为等于当前价格:

latestPrice = purchasePrice;

因此,您的复制构造函数仅传递“42.22”而不是“43.35”,并且您的副本未获得最新的价格。