Java Newbie with 72% in OCJP/SCJP - Super Confused Jobless Programmer.
I am a "newbie" too. Please verify my answers before you accept them.
My one regret in life is that I am not someone else.
- Woody Allen
Andy Jack wrote:If you make member variables private, you might need to provide getters and setters. Are there any other reasons why they are needed ?
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
meeta gaur wrote:Data encapsulation is essential in any program.
Java Newbie with 72% in OCJP/SCJP - Super Confused Jobless Programmer.
I am a "newbie" too. Please verify my answers before you accept them.
Winston Gutkowski wrote:
Andy Jack wrote:If you make member variables private, you might need to provide getters and setters. Are there any other reasons why they are needed ?
1. For access. If fields are private, nothing outside the class will be able to see them.
2. For verification. A setter can ensure that the value being set is correct.
3. Because the object is a Bean.
4. For ease of use (eg, display). It may make sense to have a getter return a field value in something other than its native form (eg, as a String).
5. To provide a 'view' of a piece of data, eg:and there's probably many more I've missed.
That said, you should not just provide getters and setters willy-nilly - especially setters. Only create them if you know that something outside the class is going to need to use them.
Winston
Java Newbie with 72% in OCJP/SCJP - Super Confused Jobless Programmer.
I am a "newbie" too. Please verify my answers before you accept them.
Andy Jack wrote:
Winston Gutkowski wrote:1. For access. If fields are private, nothing outside the class will be able to see them.
2. For verification. A setter can ensure that the value being set is correct.
3. Because the object is a Bean.
4. For ease of use (eg, display). It may make sense to have a getter return a field value in something other than its native form (eg, as a String).
5. To provide a 'view' of a piece of data,
1 - I make member variables private and put gets and sets without really understanding why i am doing all that. What is the problem in keeping every member variable public ?
2 - Yes, good point. If we don't do the verification, any code can assign any values (legal or illegal) to the member variables.
3 - Heard of beans, but don't know why beans need gets n sets.
4 - you mean something like this - a member int returned as a String ?
5 - I am not sure what that means.
I am also not sure when we must use getters and setters and when we should not.
Steve
Don't get me started about those stupid light bulbs. |