对于Java中的setter和getters,我对它何时使用组合而不是继承有疑问。这个疑问是在我解决大学作业的时候提出的。
假设我有两门课:汽车和电池。电池有3个变量(var1、var2、var3)和getter和setter。
汽车课程是这样的:
public class Car {
private String color;
private String model;
private Battery battery;
public Car(String color, String model, Battery battery) {
this.color = color;
this.model = model;
this.Battery = new Battery(battery);
}
public getBattery() {
return new Battery(battery);
}
public void setBattery(Battery battery) {
this.battery = new Battery(battery.getVar1(), battery.getVar2(), battery.getVar3());
//or this.battery = battery;
}我知道getter方法的推理(因为它与对象的引用相关),但是setter方法呢?我试着在Udemy (来自Tim )的Java课程中查找网页,但我还没有看到这个地址。
有人能帮帮我吗?谢谢!
发布于 2020-04-12 20:46:36
Car类中的三个方法中的每一个都是Battery的防御拷贝。这可以防止Car之外的任何其他对象更改Car中的Battery,因为没有其他对象会引用该特定的Battery实例(因为它总是被复制)。
习语new Battery(battery)被称为复制构造函数,因为它利用构造函数克隆对象。这是防御性复制的一个共同属性。
发布于 2020-04-12 20:26:47
就其实现方式而言,我不同意这种格式。更好的做法是编写this.battery = leave并将其保留在这个位置(而不是像问题中那样创建一个新对象并分配它的变量)。
发布于 2020-04-12 20:37:18
在某些地方,您的代码看起来很奇怪,我已经将它更改为我所期望的样子:
public class Car {
private String color;
private String model;
private Battery battery;
public Car(String color, String model, Battery battery) {
this.color = color;
this.model = model;
//Now, we're setting Car.battery to the battery that you passed in.
//Previously, you were passing the battery instance back into the Battery constructor.
this.battery = battery;
//this.battery = new Battery(battery);
}
public getBattery() {
//We want to return the battery we have above, not a new battery
return battery;
//return new Battery(battery);
}
public void setBattery(Battery battery) {
//You wouldn't do this. Just use the line you've commented out.
//No need to remake a new Battery object when you already have one passed in.
this.battery = new Battery(battery.getVar1(), battery.getVar2(), battery.getVar3());
//or this.battery = battery;
}setter方法的意义是什么?它是在您已经建造了汽车之后,在汽车实例中设置/更改电池的值。而在构造过程中使用构造函数来设置电池。
https://stackoverflow.com/questions/61177136
复制相似问题