Alex Rivera | Logout

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

Asked 2010-11-24T12:20:20.580
14

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"?

Edit
Report

1 Answer

39

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.

answered 2010-11-24T12:23:04.957

Your Answer