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?

7
  • 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? Commented Mar 13, 2014 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? Commented Mar 13, 2014 at 21:26
  • 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. Commented Mar 13, 2014 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...) Commented Mar 13, 2014 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. Commented Mar 13, 2014 at 21:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, thanks yogi. Is there any documentation I can look at that explains this logic?
Oops. looks like this is a duplicate. Perhaps the other answers can help. Help the old bear here and accept / upvote ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.