|
|
|
|
An UpdateEarlier, we talked about the visibility modifiers public and private. Now, with inheritance, we can talk about the third visibility modifier keyword:
Here's an updated discussion, including this new protected modifier: Visibility ModifiersThe keywords public and private and protected are visibility modifiers, which have the following effect: A private member of a class is visible only in methods defined within that class. A public member of a class is visible within the class where it is defined, and within all classes that are in the same package as that class. If a member is declared with no visibility modifiers, then it has default package visibility, and is visible only within the class that defines it and within classes defined in the same package. (This is analogous to the friend concept in C++ -- all classes within a package are 'friendly' to each other.) A protected member of a class is visible within the class where it is defined, and within all subclasses of that class, and also within all classes that are in the same package as that class. To summarize:
Here are some simple rules to help you choose which visibility modifiers to use, when:
NOTE: It is very good practice to always make fields/data
members within a class to be private.
I maintain that it is essential for good class design. There is
only one exception to this rule:
My approach is to take the conservative approach:
Sometimes this involves some iteration during design, where you realize that some fields or methods should become non-private (this is rare for fields, but happens more often for methods as the design evolves). | ||||||||||||||||||||||||||||||
|
This page was last modified on 02 October, 2007 |