Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you take decision to define a variable "private"?

I have attended a job interview. The interviewer asked me why you need private variable. If you achieve something by defining a variable private, can't you achieve the same by defining any other access modifier defined in java?

According to Java Specification Languages,

A private class member or constructor is accessible only within the body of the
top level class (7.6) that encloses the declaration of the member or constructor.
It is not inherited by subclasses.

But, if i am designing a class, how can i take decision to define a variable "private"?

like image 324
Shashi Avatar asked Nov 24 '10 12:11

Shashi


1 Answers

By limiting the access of "other code" (perhaps written/maintained by others) you are more free to change it in the future without having to worry about breaking some other code that relies on it.

The question is not "should I make this private?", but rather "is there a need for this to be non-private?". Is there some other code that is likely to need access to the variable?

If that turns out to be the case, you assign the proper access (possibly via getters/setters) and accept that changes to it will be difficult. Else you leave it private.

like image 113
Kris Avatar answered Sep 29 '22 23:09

Kris