Advantage of set and get methods vs public variable

63,900

Solution 1

What I have seen someday on SO, as answer (written by @ChssPly76) why to use getters and setters

Because 2 weeks (months, years) from now when you realize that your setter needs to do more than just set the value, you'll also realize that the property has been used directly in 238 other classes :-)

there are much more advantages:

  1. getters and setter can have validation in them, fields can't
  2. using getter you can get subclass of wanted class.
  3. getters and setters are polymorphic, fields aren't
  4. debugging can be much simpler, because breakpoint can be placed inside one method not near many references of that given field.
  5. they can hide implementation changes:

before:

private boolean alive = true;

public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }

after:

private int hp; // change!

public boolean isAlive() { return hp > 0; } // old signature 
 //method looks the same, no change in client code
public void setAlive(boolean alive) { this.hp = alive ? 100 : 0; }

EDIT: one additional new advange when you are using Eclipse - you can create watchpoint on field, but if you have setter you need just a breakpoint, and... breakpoints (e.g. in setter method) can be conditional, watchpoints (on field) cannot. So if you want to stop your debugger only if x=10 you can do it only with breakpoint inside setter.

Solution 2

Using public variable can cause setting wrong values to the variable as the input value cannot be checked.

eg:

 public class A{

    public int x;   // Value can be directly assigned to x without checking.

   }

Using setter can be used to set the variable with checking the input. Keeping the instance varibale private, and getter and setter public is a form of Encapsulation getter and setter is also compatible with Java Beans standard,

getter and setter also helps in implementing polymorphism concept

eg:

public class A{

     private int x;      //


      public void setX(int x){

       if (x>0){                     // Checking of Value
        this.x = x;
       }

       else{

           System.out.println("Input invalid");

         }
     }

      public int getX(){

          return this.x;
       }

Polymorphic example: We can assign Object Refernce Variable of the Sub type as Argument from Calling method to the Object Refernce Variable of Super Class Parameter of the Called method.

public class Animal{

       public void setSound(Animal a) {

          if (a instanceof Dog) {         // Checking animal type

                System.out.println("Bark");

             }

         else if (a instanceof Cat) {     // Checking animal type

                 System.out.println("Meowww");

             }
         }
      }

Solution 3

  1. Some libraries require this to fulfill the "Java Bean standard".
  2. A setter/getter can be in an interface, a property cannot be in an interface
  3. Setters/getters can easily be overridden in descended classes.
  4. setters/getters abstract away the information whether a value is calculated on demand or just an accessor to a property

Solution 4

Somewhat backwards way of looking at things.

Are there any circumstances where it's better to expose the inner workings of your class through making a member variable public, so any consumer of it can do things the designer never concieved of, leading to a feast of failure and a cornucopia of crashes?

Sort of answers itself really that one does't it?

Cornerstone principle of OO, encapsulation. A public member variable is basically global variable with a prefix...

Share:
63,900
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
Author by

zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

ADO.NET, MS SQL SERVER, Windows Forms Applications(VB and C#), Visual FoxPro, ASP.NET, WCF Web Services, Windows Mobile, and Android 2.2 & 3.0. When you sort all of Stackoverflow's members alphabetically, I am last. Check out my Android calculator. It can perform calculations in any numeral system from base 2 to base 36. It is free.Any Base Calculator Add me on google plus and I will add you into my developers circle.

Updated on April 28, 2020

Comments

  • zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
    zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz about 4 years

    Possible Duplicate:
    Why use getters and setters?

    Is there any advantage to making methods to access private variables in your class instead of making the variable public?

    For example is the second case better than the first?

    //Case 1
    public class Shoe{
        public int size;
    }
    
    //Case 2
    public class Shoe{
        private int size;
        public int getSize(){
            return size;
        }
    
        public void setSize(int sz){
            size = sz;
        }
    
    }
    
  • Antimony
    Antimony about 12 years
    There are good reasons not to use getters and setters - they clutter up the code, making it harder to read, and they violate the DRY principle. In fact, in languages with properties, it is common to just make things public (since it can be refactored into properties later if it's really necessary).
  • Tony Hopkinson
    Tony Hopkinson about 12 years
    @Antimony. Not the place for a debate, but I can't agree, not even a little bit. I've seen far too many instances were that sort 'erm shortcut, has caused way more work than just refactoring to a property. Much, much more.