Java private vs protected as a default for members

I was thinking today about an interview I recently sat in on.  The candidate was asked if they default their java member variables to protected for private.  He said private.  I have some other friends who advocate that too.

I have always been more in favor of protected.  I like to use inheritance and having protected members allows me to access those members directly.  This was in the context of a video game where I had a base sprite class with simple things such as x,y coordinates and an image.  Then I had several different types of subclasses like animated sprite and maybe even something specific as a monster class.  Having protected members worked well.

I think the answer to this question is really that "it depends".  I had a thought recently about lazy loading and protected memebers.  If your base class has a protected member that is lazy loaded (null until the getter is called), then if you try to access it in a subclass, it might be null!  If the member was declared private you would be forced to call the getter and everything would work out all right.  So if you are writing a database application or anything else where you use lazy loading, private is the way to go.


Comments

Popular Posts