1

Suppose we want to set a value of int y to 5 we generally do y=5;

int y=0;
y=5;

But if we use getter and setter than we do in following way

public class x {
private int y;
    public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}

and after that we create object of x and call its method

x x1=new x();
x1.setY(5);

My question is if we can directly set y=5 then why the use getter and setter methods

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • 4
    Your example is confused, because setting `x` to 5 changes the value of `x` - whereas calling `x1.setY(5)` changes the value of `y` within the object that `x1`'s value refers to... – Jon Skeet Sep 26 '13 at 10:14
  • 1
    possible duplicate of [Why use getters and setters?](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – Ankur Lathi Sep 26 '13 at 10:14
  • @JonSkeet Sorry I will change the question now – SpringLearner Sep 26 '13 at 10:14
  • http://programmers.stackexchange.com/questions/21802/when-are-getters-and-setters-justified – Uooo Sep 26 '13 at 10:16
  • @JonSkeet changed the question,hope its ok now – SpringLearner Sep 26 '13 at 10:16
  • 1
    Right, that makes more sense. And of course the point is that you *can't* set y directly, because it's private... which it should be, as fields are an implementation detail. – Jon Skeet Sep 26 '13 at 10:31

8 Answers8

1

If you want to have control over what values can be set use setter.

How about

cat.weight = 0  

vs

cat.setWeight(0);

and in setter you can check if weight have appropriate value

public void setWeight(int weight){
    if(weight > 0){
        this.weight = weight;
    }
    else{
       // SHOUT I dont want my cat to die
    }
}
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
1

Yes you can do direct access of the data member of the class but as per the OOPS concept the data needs to be encapsulated inside an object and we should use interfaces around the data to access it. As data is private attribute of particular object we define getters and setters as interfaces to access that data. Getters and Setter also provide a medium to hide the details of data storage and can come handy if u want to process data before every get or set operation which you cannot do by accessing the variable directly.

Udit Narayan
  • 109
  • 1
  • 7
0

It is mostly for safety reasons in computing. You always declare class variables as private variables and you can't change them for outside with x=5;. But with the setters and getters you can achieve this.

marc3l
  • 2,525
  • 7
  • 34
  • 62
0

This is most often used in object-oriented programming, keeping up with the concept of encapsulation. By keeping member variables of a class private, you can hide them and keep them from being affected by other code.

You can only modify those variables using a public member function. Setting up this interface and hiding the data or details makes it easier to read code.

You can read more here: http://en.wikipedia.org/wiki/Mutator_method

Marco Lau
  • 579
  • 2
  • 10
  • 25
0

The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.

  1. You can have only a getter. Then the property is read only. This should actualy be the most common case.
  2. You can have only a setter, making the property configurable, but communicating that nothing else should depend on its value
  3. A getter can compute a value from several fields rather than return one field.
  4. A getter can make a defensive copy
  5. A getter can perform an expensive fetch operation lazily and use a field to cache the value
  6. A setter can do sanity checks and throw IllegalArgumentException
  7. A setter can notify listeners of changes to the value

All of these things are implementation details that are hidden behind the simply "getter and setter" interface. That's what encapsulation is about.

Balaji Dhanasekar
  • 1,066
  • 8
  • 18
0

What you're asking about is one of the fundamental ideas in OOP. There's really a ton of reasons that will become a lot more obvious the more programming you do.

Encapsulation tutorial

AlyoshaKaramazov
  • 616
  • 1
  • 9
  • 25
0

Setters and getters are used as a part of best practices in Object-oriented programming. Some steps to follow are:

  • Mark all your instance variables as private.
  • Expose setters and getters
  • In your setter method, allow setting of value only after you validate the input.

By following this, you can ensure that the variables are not set to erroneous and invalid inputs.

You can have a call to validate() method in your setter, and have the logic of validating the input in that method.

Anjan Baradwaj
  • 1,219
  • 5
  • 27
  • 54
0

That's a long, long conversation to be had.

I'll just point you in the right direction here, but you need to work this out for yourself to really understand and internalize it.

One reason is that getters and setters allow you to protect yourself. You control what happens when the variable is modified.

You could, for example, decide to refuse some values - maybe your field needs to be a positive int, say. You cannot trust callers to respect that constraint (rule 1 of programming, do not trust anyone) and need to enforce it, possibly with an assertion. A setter allows you to validate the value before actually modifying it. Direct access lets callers put illegal values in your class outside of your control - and since it can happen, it will happen.

Another reason is abstraction: if you expose the field, you're stuck with your representation forever. You might find a better, more optimal representation later, but you cannot change it since you've given callers direct access to your field - they now rely on its type. Hiding the implementation details behind getters and setters, on the other hand, allows you to change your internal representation without breaking your external contracts - just modify the getter and no one ever needs to know.

Nicolas Rinaudo
  • 6,068
  • 28
  • 41