Java getter setter 方法

Java getter setter method

我正在编写一个程序来计算地毯安装的成本。我正在努力为以下变量编写 setter getter 消息...labourCharge、price 和 postCode。

这就是您编写代码的方式。假设您的 class 是 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 的其他属性做同样的事情。

您只需要在 class 中创建一个 getter/setter

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

在intellij idea中通过组合alt+insert的方式生成getter和setter很方便,其他工作室的开销我不知道