How does the access specifiers like private, public, etc. help in code re-usability?
i got this question for an interview and i were not able to find the ans. plz help me.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are several fine lines around this, with which I could answer the question a few different ways.
Consider the case where a developer marks just about everything as private. It may have been a perfectly good class that could have been reused if only I could have extended it and overridden the
doSomething()method. However, since the method has been marked private, my hands are tied. This will cause many developers to copy & paste the entire class, changing the one necessary part. (Not cool.) So it could be seen that marking everything as private prevents reuse.However, on the other hand, consider the case where a developer marks everything as public. That developer or other developers start writing extension classes, or calling all of the various methods / accessing attributes which maybe should have been marked protected / private. A design bug or such is found, which requires the class to be modified. However, since it was written so “open”, what may have been a simple fix is now much more complex, as all of the additional references have to be found and considered.
I think the best option is a compromise. Mark things that are designed to be used by client code as “public”. Mark things that have no business being extended / overridden as “private”. If there is something that could prove useful to someone in the future to extend, mark it as “protected”. And always add Javadocs to further signal your intentions.