next up previous
Next: More Keywords Up: The Frightened Freshers Guide Previous: Writing Good Documentation

Public and Private

So far, you know that you can have public and private methods and variables. But you do not really know why you would want to use one over the other yet. Public Class Variables can be accessed and modified outside of the Class by other Classes, public methods can be called from outside of the Class by an object of that Class. On the other hand, private methods and variables are somewhat more uptight about who uses and abuses them and will only let the Class they were created in call them. They are not visible from the outside. If you remember about the Class interface in the javadoc, none of the private methods internal to the Classes are shown.

There is a very good reason for this! This tactic of Information hiding hides what the user does not need to or is not allowed to know. After all, you wrote the Class and you dont want some other evil Class to come in and muck around with your Variables! Now might be a good time to introduce coupling.

No, not the BBC TV programme that was on a while ago. Coupling refers to how tightly integrated one Class is to another. If you make a small change to one class, it should not utterly destroy the workings of another class. This is called Loose coupling and according to Matthieus lecture slides `Should be aimed at, even if we write both the used and the user class'.

So why use private methods at all? We have seen that they can not be called outside of the Class that created them, thats all well and good. Its part of a tactic in programming called divide and conquer. If you have some supercomplex method that you are writing it might be easier to break it down into logical steps and have each step in its own private method. This also makes programs somewhat easier to debug and I highly recommend that you break down any huge long methods into something shorter (If you are having difficulty that is. Otherwise, do so anyway because it makes code easier to read!).

You can also put things as Private methods when they would be dangerous for other Classes to access (Imagine a DeleteEverythingEver method that was public - a nasty evil Class could call this and inadvertantly delete everything!)


next up previous
Next: More Keywords Up: The Frightened Freshers Guide Previous: Writing Good Documentation
Tom Carlson 2006-01-10