Not Using Protected Keyword
jsf, software development, websphere
OK, I admit it I’m a simpleton when it comes to scoping things in Java. Out of all four possible keywords for scoping access I manage to use two:
- public
- private
I realize there’s probably a good reason where I’d want to use protected or default scope, but I just haven’t run across one. I find sticking to private and public simplifies my designs. It is very clear whether the variable or method was supposed to be encapsulated by the class. Since I don’t do APIs if I need access then it generally might as well be public.
When I do run across a protected or default in example code I often wonder if there was an explicit reason for it. It turns out that IBM’s RAD 6.0 writes all its JSF backing bean methods as protected scope, though I still don’t get why.
Of course I may also just be missing some blindingly obvious OO concept that makes protected really cool.
Ed Gibbs @ June 12, 2006


i don’t think you’re missing out on much. i save protected for special occasions, like when i have a class hierarchy and intend that a method should be called only by its subclasses.
There’s an interesting (esoteric?) example of an explicit use of default scope in the Java SDK source code. Open up your JAVA_HOME/src.zip, and pull up the WindowsPreferences.java. If you look at Preferences.java, it uses “java.util.prefs.WindowsPreferences” as the default implementation if you’re on Windows. You can’t instantiate that class directly, though. Only the classes in java.util.prefs can. Like you said, you’re not writing API, so it’s mainly an academic example. It is an interesting technique for providing a default, without letting anyone else use (or extend?) it. I don’t think I’ve ever seen anyone else use it, and I don’t recall using it at all myself. I guess it’s only something for guys like Josh Bloch writing widely published APIs.