gpt4 book ai didi

java - 在 OOP 中为类编写复制方法

转载 作者:行者123 更新时间:2023-12-01 23:26:39 25 4
gpt4 key购买 nike

假设我有一个汽车类别,这是它的代码:

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

}

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

不添加 Setters 方法。

最佳答案

试试这个:

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

关于java - 在 OOP 中为类编写复制方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com