0

In my CS class I am just learning about classes and OOP.

So when you create a class you initialize a certain number of private variable.

I know you make them private because if they were public they would be easily changeable and could lead to a lot of bugs.

So we use get and set methods to change the variable. But that once again makes the variables very easy to change right? So whats the point of making them private in the first place?

nem035
  • 34,790
  • 6
  • 87
  • 99
Natantantan
  • 47
  • 2
  • 8

8 Answers8

6

Some benefits of using getters and setters (known as encapsulation or data-hiding):

1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.

Example:

class EncapsulationExample {
    private int readOnly = -1;  // this value can only be read, not altered
    private int writeOnly = 0;    // this value can only be changed, not viewed
    public int getReadOnly() {
        return readOnly;
    }
    public int setWriteOnly(int w) {
        writeOnly = w;
    }
}

2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.

Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.

Example (getting a value):

class EncapsulationExample {
    private int value;
    public int getValue() {     
        return value; // return the value
    }
}

Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:

class EncapsulationExample {
    private int value;
    public int getValue() {
        return value*2; // return twice the value
    }
}

3. Makes the code cleaner, more readable and easier to comprehend.

Here is an example:

No encapsulation:

class Box {
    int widthS; // width of the side
    int widthT; // width of the top
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.widthS;  // Hm... what is widthS again? 
int w2 = b.widthT;  // Don't mistake the names. I should make sure I use the proper variable here!

With encapsulation:

class Box {
    private int widthS; // width of the side
    private int widthT; // width of the top
    public int getSideWidth() {
        return widthS;
    }
    public int getTopWIdth() {
        return widthT;
    }
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!

Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).

Here is good SO thread on this topic.

Here is good read on data encapsulation.

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
  • What about the scenario where you are providing both get and set and don't need to manipulate it at the set or get stage.I don't understand why you would want a different name in the getter anyway as shown in your example, why not just change the real name of the variable. Wouldn't it be better to have consistent names? Is it worth doing encapsulation even if your use case is very simple and there is no apparent upside to getters/setters? – slaw Apr 21 '16 at 23:35
  • It all depends of the particular use case although in general consistent naming usually is better. And my examples are simple on purpose to demonstrate encapsulation in a few out of many possible situations. If all you have in your code is a few variables then encapsulation might be an overkill. – nem035 Apr 22 '16 at 00:59
1

As the above comment states, getters and setters encapsulate (i.e. hide) inner details of your class. Thus other classes that interact with yours, do not need to know about the implementation details.

For example, in the simple case you describe, instance variables are exposed via getters and setters. But what if you wanted to change your class so that you no longer used instance variables, but rather you persisted the values to disk. You could make this change to your class without affecting the users of your class.

Keep in mind also that getters and setters need not always be provided. If you do not want your class to provide a way to set or read these properties, then don't. Simply make them private.

EJK
  • 12,332
  • 3
  • 38
  • 55
0

get is used to obtain a value for an attribute and set is used to put a value to an attribute ex:

private int variable;

public int getVariable(){
   return variable;
}

public void setVariable(int aux){
   variable=aux;
}

In general, is used to encapsulate an attribute.

reference:

Set and Get Methods in java?

Community
  • 1
  • 1
0

Encapsulation or data hiding gives u more control on what values can be set to a field. Here is an example if you don't want a class attribute to have a negative value:

class WithoutGetterSetter {
   public int age;
}

class WithGetterSetter {
   private int age;
   public setAge(int age) {
      if(age < 0)
        // don't set the value
      else 
         this.age = age;
   }
}


public class testEncapslation {
   public static void main(String args[]) {
      WithoutGetterSetter withoutGetterSetter = new WithoutGetterSetter();
      withoutGetterSetter.age = -5;

      WithGetterSetter withGetterSetter = new WithGetterSetter();
      withGetterSetter.setAge(-5); 
   }
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • So you are saying that get and set are for if you want to do more than just set or get the variable like if you want to check for stuff before getting or setting the variable? but if my set method is just age=age i might as well make age public? – Natantantan Oct 16 '14 at 02:11
  • There are more than just one benefit as others have mentioned. – Juned Ahsan Oct 16 '14 at 02:12
0

Get and Set methods are preferable to "public" variables because they insulate the users of a class from internal changes.

Supposing you have a variable "StockQty" and you made it public because that seemed like the easiest thing to do.

Later on you get a user requirement to track the history of stock over time. You now need to implement a SetStockQty() method so you can save the old quantity somewhere before setting the new quantity.

Now all the users of your class have to change there code, re-document and re-test.

If you had SetStockQty() method to begin with only you would need to change and test your code.

The second reason is you can have Getters without Setters effectivly making the variable "read only".

James Anderson
  • 27,109
  • 7
  • 50
  • 78
0

Traditionally, they are justified in terms of encapsulation. By providing moderated access to read and write the fields of a class, we supposedly reduce coupling.

In simpler language: by controlling the ways in which other classes can read and change our data, we reduce the ways in which our class's data can change. This means that the connections between classes are reduced, which reduces complexity.

However, the same logic says that getters and setters should generally be avoided unless there's an actual need for them, and there very seldom is such a need. For the most part, a class should "tend to its own knitting" - if there's a calculation to be done on this class's data, it should do it. If a value should be changed, it should do the changing.

For example, consider an object in space. It has a location specified as (x,y,z). We could possibly allow other classes to just set those arbitrarily - this would be horrible, obviously, but it's not obvious that a setter for these would be any better. What you really want is a constructor to set an initial position, and then methods to influence that position - for example, to register an impact or an acceleration. Then you're doing OO programming.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

One word, Encapsulation.setters also allow you to control how values are entered into your program. Many new programmers like myself are often confused by this concept. I strongly advice you read this SO question

Community
  • 1
  • 1
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
0

Being objective: it's all about best pratices!!!

1) IF necessary, expose your attributes with get methods. 2) IF necessary, allow attribute modification (state modification) using set methods;

Have both public get and set methods without treatment is the same as have the attributes public.