Private Variables
What is the use in declaring a variable as private . Because if the user has to modify the variable we have to provide the user with get and set methods .
He will declare an Object of that class and calls set /get methods. Instead we could have declared that variable as public and allow him to change directly?Is it something to do with "DataHiding" . If so how?
[376 byte] By [
Manthanaa] at [2007-11-27 7:29:33]

> What is the use in declaring a variable as private .
> Because if the user has to modify the variable we
> have to provide the user with get and set methods .
Users don't modify variables. Code does. Often times good design dictates that no code outside the declaring class should be able to directly access a variable. So we make it private. Google for encapsulation or data hiding.
> He will declare an Object of that class and calls set
> /get methods. Instead we could have declared that
> variable as public and allow him to change
> directly?Is it something to do with "DataHiding" . If
> so how?
Googlel for "why get and set are evil" or something like that. The author claims that get and set methods are no better than simply making the variables public. His comments are a bit extreme, but there's some truth to what he says.
If you just blindly add get/set for every variable, then, yes, there's no point in making them private. However, you can do things with public methods on private variables that you can't do with public variables--change the underlying implementation, do validation of set values, compute values on the fly for get values. Get/set don't always have to simply be this.x = x or return x.
jverda at 2007-7-12 19:09:42 >
