Java Reference
In-Depth Information
NOTE Remember that a class itself can be specified as public . This makes the class access-
ible from any package anywhere. A class that is not declared as public can be accessed only
fromclasseswithinthesamepackage.Thismeans,forexample,thatyoucannotdefineobjects
ofanon- public classtypewithinclassesinotherpackages.Italsomeansthattoderiveanew
class from a class in a different package, the base class must be declared as public . If the
base class is not declared as public , it cannot be reached directly from outside the package.
As you can see from Figure 6-2 , a subclass that you define in the same package as its base class inherits
everything except for private data members of the base. If you define a subclass outside the package con-
taining the base class, the private data members are not inherited, and neither are any data members in the
base class that you have declared without access attributes. Members defined as private in the base class
are never inherited under any circumstances. The base class, MyClass , must be declared as public in Pack-
age1 , otherwise it would not be accessible from Package2 as the base class for SubClass2 .
You should also be able to see where the explicit access specifiers now sit in relation to one another. The
public specifier is the least restrictive on class members because a public member is available everywhere,
protected comes next, and prevents access from classes outside of a package, but does not limit inheritance
— provided the class itself is public . Putting no access specifier on a class member limits access to classes
within the same package and prevents inheritance in subclasses that are defined in a different package. Be-
cause of this, class members without an access specifier are often referred to as package-private . The most
restrictive is private because access is constrained to the same class.
The inheritance rules apply to members of a class that you have declared as static — as well as non-
static members. Recall that only one occurrence of each static variable in a class exists and is shared by
all objects of the class, whereas each object has its own set of instance variables. So, for example, a variable
that you declare as private and static in the base class is not inherited in a derived class, whereas a vari-
able that you declare as protected and static are inherited and are shared between all objects of a derived
class type, as well as objects of the base class type.
Hidden Data Members
Search WWH ::




Custom Search