next up previous contents
Next: Exception handling Up: Java Interlude 2 Parameter Previous: Packages   Contents

The protected modifier

In addition to public, private and no modifier (implicitly indicating package visibility), there is another modifier called protected, indicating visibility within the inheritance subtree rooted at a class--that is, the collection of all classes that directly or indirectly extend the current class.

While the usefulness of protected mode instance variables is doubtful, it does make some sense to have protected mode functions, that can be used by subclasses that can be ``trusted'' to know what these functions are doing, but not by arbitrary classes outside the subtree.

It is allowed for a subclass to promote a function from protected to public while redefining it. Note that this is a specific exception to the general rule that says that a subclass is not allowed to change the visibility of a function when redefining it. (It is also not permissible for a subclass to change the return type of a function when redefining it.)

One concrete example where this is used is in the function clone() defined in Object. As we have already noted, clone() makes a bitwise copy, which is not necessarily the correct way to clone an object, so the clone() method checks that the calling class implements the marker interface Cloneable() to verify that the programmer actually intends that clone() be used.

As a further precaution against accidental misuse, clone() is declared to be protected in Object. This means that by default, even after implementing the Cloneable interface, only subclasses can invoke clone() on objects of a given class. To make an object fully cloneable, the class must redefine clone() with the modifier public.


next up previous contents
Next: Exception handling Up: Java Interlude 2 Parameter Previous: Packages   Contents
Madhavan Mukund 2004-04-29