Java getter setter method [duplicate]

问题描述 投票:0回答:3

此问题已经在这里有了答案:

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

java getter-setter
3个回答
0
投票

您只需要在类内创建一个吸气剂/设置剂

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

1
投票

这是您应该编写代码的方式。假设您的课程是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的其他属性执行相同的操作。


0
投票

intellij的想法很方便,通过组合alt + insert来生成getter和setter,而以其他我不知道的工作室为代价

© www.soinside.com 2019 - 2024. All rights reserved.