-2

Possible Duplicate:
Why use getters and setters?

I have been seeing contsructors for a while now,I still dont know how things like this work,I have little knowledge of java and I know they are getters and setters but which function exactly do they perform in my code because it seems its just referring to itself not performing a specific block of code I just need a very simple explanation,Not seeking debates.

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;
    }
}
Community
  • 1
  • 1
  • see http://stackoverflow.com/questions/12098636/what-is-the-use-of-getter-and-setter-method/12098728#12098728 and http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Nandkumar Tekale Sep 25 '12 at 09:39
  • 1
    Its very basic concept. Take a looks at http://en.wikipedia.org/wiki/JavaBeans – MoveFast Sep 25 '12 at 09:41
  • 5
    getters and setters will make more sense when you make your variables declared inside the class "private", then to access then anywhere you will need getters and setters – AurA Sep 25 '12 at 09:41

6 Answers6

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

If you are calling constructor in the way you mentioned above, you are setting the values of the variables; so the setter methods you created have no significance. If you want to make your setter methods useful, create an empty constructor and then use these functions.

Shafi
  • 1,368
  • 10
  • 24
0

Getter and Setter is a way of implementing Object Oriented Principle of Encapsulation.

- Encapsulation in its most basic form is like having private fields with public Getter and Setters.

- The most important reason for using Getter and Setter is to implement Validation of the data that is passed to the fields.

Eg:

In the below example there is No getter and setter , so the weight of the Dog can be set to an invalid value of -10

public class Dog{


   int weight;

    public static void main(String[] args){

                    new Dog().weight = -10;

           }


 }

Eg:

I am now using Setter and Getter to validate the field weight

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

               }


     }
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • 4
    You should reformat that code. The indentation is really bad. And I think you are overusing **bold** and `code blocks`. – maba Sep 25 '12 at 10:02
  • @maba sorry if the indentation is not that good, but as i have typed this from my mobile phone, i hardly have any choice.... – Kumar Vivek Mitra Sep 25 '12 at 10:05
  • 1
    "Encapsulation in its most basic form is like having private fields with public Getter and Setters". I think encapsulation in its most basic form is *hiding* the implementation. As such basic setters/getters seem to violate this principle – Brian Agnew Sep 25 '12 at 10:12
  • Encapsulation also means preventing some wrong value to be set to the fields, isn't it ? – Kumar Vivek Mitra Sep 25 '12 at 10:15
  • I would rather you kindly give me an example that doesnt make use of Conditions in the constructor – Jerry Guzman Sep 25 '12 at 10:36
  • @BrianAgnew : i.e. Data/Information Hiding concept, which was separated from [Encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)) – Nandkumar Tekale Sep 25 '12 at 10:47
  • @KumarVivekMitra : Encapsulation only means `binding object state and behavior together`. – Nandkumar Tekale Sep 25 '12 at 10:50
  • I am not sure who deduced my point, but just to bring few things in lime light i would like to show these 2 answers... http://stackoverflow.com/questions/5038336/confused-with-java-encapsulation-concept and this... http://stackoverflow.com/questions/1345753/what-are-the-uses-of-getter-setters-in-java – Kumar Vivek Mitra Sep 25 '12 at 16:10
  • @KumarVivekMitra : I am not a down voter but see wiki link http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming). It clearly tells `The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition.` – Nandkumar Tekale Sep 26 '12 at 06:06
0

In this case you don't need Getters/Setters, but still it is always good to use them. If you notice later that you want to check for bounds while setting. Or when you are getting s.th. you might want to perform some data conversions.

Another simple example: You just want to set a value during construction of the element, so you just don't implement a setter but you implement a getter (as well, always set those member variables to private, otherwise Setters/Getters are pretty pointless).

So in most cases you probably won't need them, but it is still a good idea to always use Setters/Getters (imo)

Philipp Wendt
  • 2,538
  • 1
  • 15
  • 17
0

Your parameterized constructor is initializing your member variables

  • String _title;
  • String _link;
  • String _description;
  • String _pubdate;
  • String _guid;

The role of getter and setter is to read and write values from and to these member variables. They are more a standard to be followed as it is widely used in many Java based frame works.

sharadendu sinha
  • 827
  • 4
  • 10
0

Getters and setters provide protection from access to your variables. You can use getters and setters with different levels of visibility for different user groups, and greater flexibility in your code. That does not mean every variable needs a getter and setter. Think of them more for the levels of access they can provide and the features you can build into their respective levels of access. Here is a class named 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;

}
gh.
  • 339
  • 1
  • 3
  • 20