**Object的clone方法可以帮助我们克隆对象。现在需编写一个类Car包含: 1.属性: private String name; private CarDriver driver; private int[] scores; 2.无参构造函数 public Car() { } 3.方法: @Override public String
**Object的clone方法可以帮助我们克隆对象。现在需编写一个类Car包含:
1.属性:
private String name;
private CarDriver driver;
private int[] scores;
2.无参构造函数
}
3.方法:
public String toString() {
return “Car [name=” + name + “, driver=” + driver + “, scores=” + Arrays.toString(scores) + “]”;
}
setter/getter方法与clone方法。注意:clone方法需实现对象的深度克隆。
CarDriver为已经定义好的类,部分代码如下:
class CarDriver {private String name;
public CarDriver() {}
//setter/getter
//toString
}
/ 请在这里填写答案,即Car类的完整代码 /**
{
private String name;
private CarDriver driver;
private int[] scores;
public Car() {
}
@Override
public String toString() {
return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CarDriver getDriver() {
return driver;
}
public void setDriver(CarDriver driver) {
this.driver = driver;
}
public int[] getScores() {
return scores;
}
public void setScores(int[] scores) {
this.scores = scores;
}
@Override
protected Car clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Car car = new Car();
CarDriver D = new CarDriver();
if(driver==null)
D=null;
else
D.setName(driver.getName());
car.setDriver(D);
String Nm;
if(name==null)
Nm=null;
else
Nm=name;
car.setName(Nm);
if(scores==null)
car.setScores(null);
else
{
int c[] = Arrays.copyOf(scores, scores.length);
car.setScores(c);
}
return car;
}
}