此问题已经在这里有了答案:
我正在制作一个程序来计算地毯的安装成本。我正在努力为以下变量写一个setter getter消息... labourCharge,price和postCode。
您只需要在类内创建一个吸气剂/设置剂
public class CarpetCostEstimator {
double price = -1.0;
String postCode = "XXX-XXX";
double labourCharge = 1.0;
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public double getLabourCharge() {
return labourCharge;
}
public void setLabourCharge(double labourCharge) {
this.labourCharge = labourCharge;
}
}
这是您应该编写代码的方式。假设您的课程是CarpetCostEstimator。构造函数采用labourCharge,postCode和price这三个值并将其设置如下:
public CarpetCostEstimator(double labourCharge, String postCode, double price) { this.price = price; this.postCode = postCode; this.labourCharge = labourCharge; } public double getLabourCharge() { return this.labourCharge ; } public void setLabourCharge(double labourCharge){ this.labourCharge = labourCharge }
在上面的代码中,我向您展示了如何为labourCharge放置setter和getter,您可以对price和postCode的其他属性执行相同的操作。
intellij的想法很方便,通过组合alt + insert来生成getter和setter,而以其他我不知道的工作室为代价