Re: What's the use of private?
Jeff.M wrote:
Unless I'm mistaken, private things are inaccessible to everything
else, even subclasses. And it seems that using private makes it
difficult, if not impossible, to extend the class. Protected, on the
other hand, is just like private except that extending classes can use
protected things.
I can't think of any scenario where private would be a better choice
than protected. So what's the use of private?
Public, package-protected, and protected methods and variables all make
up part of the API for a class. Once you have made a method or variable
any of these types, it becomes a part that *anyone* could use or modify.
You lose some defensiveness. An example helps here:
Suppose that a class, say Widget, has to perform some hairy magic with a
native object peer. People can extend this Widget class to perform
specific tasks, but they don't need to know how to get from Widget's API
to this peer object. Especially, they shouldn't be touching this peer
object. So Widget makes this object peer private to stop people from
touching it.
In addition, variables should almost always be marked private, since
that allows the class to meter access to them for sanity checks and whatnot.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth