1) Protected is for situations you will rarely, if ever, encounter – keeping methods from being implemented in a subclass
2) Public is for when you write a method that you want everybody to call
3) Private is for methods that you only ever want called from this specific class
4) No-modifier (default or package) is appropriate for almost everything – it allows your method to be called by other classes in your package, but not by other folks’ classes (in other packages)
I mentioned that I had on occasion abused those rules when using classes written by others. A couple times, I created an empty folder hierarchy in my project that mirrored someone else’s package and created my class there so I could use their package-access resources. For example, I once extended sun.net.ftp.TransferProtocolClient, creating my own FTPClient class with the addition of methods to do such things as proxy login, make directory, make path and chmod. That was in 2003, when Sun was pretty strict about the sun.* packages and classes. I just now edited that FTPClient code in Eclipse, referring to a new JDK and found that not only does sun.net.ftp.FtpProtocolException no longer extend IOException (requiring major code updates); but also, I can extend TransferProtocolClient in a different package with no problem. In this case, I no longer need to mirror the original package in order to extend the class – and I conclude that the resources I need to access are no longer package-protected, they are public.
No comments:
Post a Comment