0

I'm fairly new to Java -- can someone please give an applicable reasoning for what the Getter and Setter methods's purposes are respectively?

Doesn't it seem redundant to create two different methods in a class to receive data and apply the data? Why aren't they consolidated into one method?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Ray
  • 23
  • 2
  • 6
  • How exactly would you create *one* method, when there are two different operations: one to fetch data and one to set it? What would you pass in as the argument if you just wanted to fetch the existing value? – Jon Skeet Mar 13 '14 at 21:25
  • couldn't you essentially get the data and store it in a single variable and just return the values of that variable? There seems to be a gap in my understanding... can someone please clarify what i'm not understanding? – Ray Mar 13 '14 at 21:26
  • The only point where I see usable to return anything from a getter is implementing [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface), but you return the current instance of the class, not the value of the parameter being passed. – Luiggi Mendoza Mar 13 '14 at 21:28
  • 1
    Then how would you set it? I really can't understand what you're proposing. It would help if you'd give two versions of a class, both with a single `int` field called `value`. One version of the class has `getValue` and `setValue` methods, and the other is whatever you're proposing. – Jon Skeet Mar 13 '14 at 21:28
  • 3
    (I don't think this is a duplicate, by the way - the OP isn't talking about encapsulation, but about having one method rather than two...) – Jon Skeet Mar 13 '14 at 21:29
  • 1
    This is really a Object Oriented Programming Question. Best place to start is Understand Encapsulation. Messages versus Data Members and how they should be managed especially within the contexts of aggregation and inheritance. – myqyl4 Mar 13 '14 at 21:30
  • @myqyl4: No, I really don't think so. The OP isn't saying "why not just expose the field directly?" - he's saying "Why not have just one method?" – Jon Skeet Mar 14 '14 at 06:48

1 Answers1

0

Not at all. A getter can have significantly relaxed implementation to a corresponding setter: the setter may have different access privileges and can prevalidate any of the input data.

This helps achieve much better program stability.

P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • Interesting, thanks yogi. Is there any documentation I can look at that explains this logic? – Ray Mar 13 '14 at 21:29
  • Oops. looks like this is a duplicate. Perhaps the other answers can help. Help the old bear here and accept / upvote ;-) – P45 Imminent Mar 13 '14 at 21:30