• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why public setters/getters for a private class variable instead of public class variable ?  RSS feed

 
Myke Enriq
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a job interview question , I can tell that the guy asking me this is very smart , and he really knows Java (dropped my jaw when we talked about algorithms for example).

He asks me this question: If I make a class with a private int x member , and create public setters and getters , what is the reason to do this and not just make x public.

On the spot , I came up with a few reasons:
- in some situation you need a private member and a public get , but no set function , like in the singleton pattern
- if you make setters and getters and a no argument constructor , you can create a bean out of that class
- you can synchronize the setters and getters , or at least a part of the code inside them

Anyway , can you come up with more reasons why it is more useful to make a private member variable with public setters and getter instead of that member variable being public ?

PS: by class variable and member variable I mean the variable x in:
class MyClass{
int x;
}
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're hiding the implementation. They might be simple getters and setters now, but you never know when you might want to change something in the future. E.g. derive the value from something else, or add validation. Once you've exposed the implementation you can't go back without potentially large impact elsewhere.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Moving this topic to the general java forum -- as this has nothing to do with programming diversions.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!