0

假设我有一个Car 类,这是它的代码:

public class Car {
    private String make;
    private String model;
    private int year;

    public Car()
    {
        this.make = "";
        this.model = "";
        this.year = 0;
    }

    public Car(Car c)
    {
        this.make = c.getMake();
        this.model = c.getModel();
        this.year = c.getYear();
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    /* Trouble here */
    public Car copy(Car c)
    {
        return c; // But needs all properties to be same as current instance of class.
    }

}

请注意,我的私有字段没有 Setter 方法。有没有一种Copy(Car c) 方法可以将我的实例复制到相同类型的目标对象中并返回目标对象?

不添加 Setters 方法。

4

3 回答 3

2

尝试这个:

public Car copy(Car c)
{
    c.make = this.make;
    c.model = this.model;
    c.year = this.year;
    return c; // But needs all properties to be same as current instance of class.
}
于 2013-11-09T15:58:55.683 回答
1

这通常是通过使用您已经实现的Copy Constructor来完成的。

Car car = new Car();
Car copiedCar = new Car(car);

如果您想使用方法来执行此操作,可以从方法内部调用复制构造函数。

public Car copy(Car c)
{
    Car copiedCar = new Car(c);
    return copiedCar;
}
于 2013-11-09T16:02:37.600 回答
0

访问控制按范围工作;类中的代码Car可以访问所有Car实例的所有私有属性,无论它们来自何处。

public Car copy(Car c)
{
    c.make = this.make;
    c.model = this.model;
    c.year = this.year;
    return c;
}
于 2013-11-09T16:02:46.420 回答