-2

可能重复:
为什么要使用 getter 和 setter?

我已经看到了一段时间的构造函数,我仍然不知道这样的事情是如何工作的,我对 java 知之甚少,我知道它们是 getter 和 setter,但它们在我的代码中究竟执行了哪个函数,因为它似乎只是指对于自己不执行特定代码块我只需要一个非常简单的解释,而不是寻求辩论。

public class RSSItem {

    // All <item> node name
    String _title;
    String _link;
    String _description;
    String _pubdate;
    String _guid;

    // constructor
    public RSSItem(){

    }

    // constructor with parameters
    public RSSItem(String title, String link, String description, String pubdate, String guid){
        this._title = title;
        this._link = link;
        this._description = description;
        this._pubdate = pubdate;
        this._guid = guid;
    }

    /**
     * All SET methods
     * */
    public void setTitle(String title){
        this._title = title;
    }

    public void setLink(String link){
        this._link = link;
    }

    public void setDescription(String description){
        this._description = description;
    }

    public void setPubdate(String pubDate){
        this._pubdate = pubDate;
    }


    public void setGuid(String guid){
        this._guid = guid;
    }

    /**
     * All GET methods
     * */
    public String getTitle(){
        return this._title;
    }

    public String getLink(){
        return this._link;
    }

    public String getDescription(){
        return this._description;
    }

    public String getPubdate(){
        return this._pubdate;
    }

    public String getGuid(){
        return this._guid;
    }
}
4

6 回答 6

2

The constructor is performing the initialisation of the object in one atomic operation. When you call a constructor, upon return you have a completely created object. Compare this with a simple no-args constructor, followed by a chain of setters. In this scenario you can easily create an object incompletely.

Should you use an intelligent constructor taking args and building the object completely rather than a series of setters ? Generally, yes. Here's why:

  1. the operation is atomic and will give you a complete, correct object (I'm assuming you validate the inputs)
  2. you can provide overrides to create objects from fields, strings/streams etc.
  3. by using the final field you can create immutable objects. This is very useful for determining reliability (especially wrt. threads) and for debugging issues.

Generally I view sets of setters/getters as poor OO design. At their most basic they merely expose internal fields. You can provide validation etc., but you're still potentially exposing the implementation.

I would rather instantiate the object using a constructor, and then ask it to do things for me using well-defined methods, rather than pulling the data out via getters and doing it myself. This is the overall aim of OO - telling objects to do things for you rather than asking them for data and doing it yourself.

于 2012-09-25T10:02:32.950 回答
0

Getter并且Setter是实现面向对象原则的一种方式Encapsulation

- Encapsulation最基本的形式就像拥有private fieldswith public Getter and Setters

-使用的最重要原因Getter and Setter是对传递fields.

例如:

在下面的示例中,没有 getter 和 setter,因此可以将 Dog 的权重设置为 -10 的无效值

public class Dog{


   int weight;

    public static void main(String[] args){

                    new Dog().weight = -10;

           }


 }

例如:

我现在使用 Setter 和 Getter 来验证字段权重

public class Dog{


       int weight;

  public void setWeight(int i){

    if(i < 0){                        // Validation

           System.out.println("Invalid weight");

      }              

    else{
        this.weight = i;

     }

 }


  public int getWeight(){

       return this.weight;

 }

        public static void main(String[] args){

                        new Dog().setWeight(50);

               }


     }
于 2012-09-25T09:45:13.410 回答
0

在这种情况下,您不需要 Getters/Setters,但使用它们总是好的。如果您稍后注意到您想在设置时检查边界。或者当你得到 s.th. 您可能想要执行一些数据转换。

另一个简单的例子:你只是想在元素的构造过程中设置一个值,所以你只是不实现一个 setter 但你实现了一个 getter(同样,总是将这些成员变量设置为私有,否则 Setters/Getters 是毫无意义的)。

因此,在大多数情况下,您可能不需要它们,但始终使用 Setters/Getters (imo) 仍然是一个好主意

于 2012-09-25T09:45:24.337 回答
0

您的参数化构造函数正在初始化您的成员变量

  • 字符串_标题;
  • 字符串_链接;
  • 字符串_描述;
  • 字符串_pubdate;
  • 字符串_guid;

getter 和 setter 的作用是从这些成员变量中读取和写入值。它们更像是一个需要遵循的标准,因为它广泛用于许多基于 Java 的框架作品中。

于 2012-09-25T09:45:29.777 回答
0

Getter 和 setter 提供保护以防止访问您的变量。您可以为不同的用户组使用具有不同可见性级别的 getter 和 setter,并在代码中提供更大的灵活性。这并不意味着每个变量都需要一个 getter 和 setter。更多地考虑它们可以提供的访问级别以及您可以在各自的访问级别中构建的功能。这是一个名为 Sample 的类:

public class Sample {
   public static final int DEFAULT_QTY = 8;

   /**Create object with qty = 0*/
   public Sample(){
      setQty(DEFAULT_QTY);
      //this.qty = DEFAULT_QTY;//here makes no difference
   }

   /**Create object with qty if qty > 0*/
   public Sample(int qty){//drops confusion created by this.qty vs qty
      //provides built-in range protection through the constructor's use of setter
      setQty(qty);
   }

   /**@param qty The qty to set for this object, must be > 0*/
   public void setQty(int qty){
   if(qty > 0) {
       this.qty = qty;
   else {
      informUser(QTY_MUST_BE_>_0);
      //setQty(0); or getValidInput();
      }
   }

   /*@param forSureQty The pre-verified value to set for qty*/
   protected void setQtyNow(int forSureQty) {
       this.qty = forSureQty;
   }

   /**@return Returns the qty if qty < qtyAvailable, returns -1 otherwise*/
   public int getQty(){
      //Avoid problems with the computer selling more than you have available
      if(getQtyAvailable < this.qty) {
         //informUser(QTY_AVAILABLE = x QTY_NEEDED = >x);
         return -1;
      }
      return this.qty;
   }

   /*@return Returns the value of qty for this object*/
   protected getQtyNow()
      return this.qty;
   }

  private int qty;

}
于 2012-09-25T10:20:09.983 回答
0

如果您以上述方式调用构造函数,则您正在设置变量的值;所以你创建的setter方法没有意义。如果您想让您的 setter 方法有用,请创建一个空的构造函数,然后使用这些函数。

于 2012-09-25T09:43:43.623 回答