(^344) | Inheritance, Polymorphism, and Scope
import one.*;
packagetwo;
public classDerivedClass extendsSomeClass
{
voiddemoMethod(SomeClass param1, DerivedClass param2)
{
param1.someInt = 1; // Generates a compiler error
// Can't access member of instance of SomeClass
param2.someInt = 1; // This access is legal
// It refers to the inherited member
}
}
The compiler will issue an error message for the first assignment statement because it
is illegal to access the protectedfield of a superclass when the superclass resides in a different
package. The second assignment is valid because it refers to the inherited field within
DerivedClass.
The protectedmodifier provides the least restrictive level of access that isn’t public.We
use protectedto enable users to extend our class with a subclass. The subclass inherits its
own copies of the protectedmembers, but cannot access the originals.
It is unusual to see protectedin an application designed with CRC cards because all of
the responsibilities and collaborations are known in advance. But if a package of classes is
independent of an application (such as the java.utilpackage), it is often desirable to enable
users to derive their own classes from the library classes.
Package Access When no access modifier is specified, then classes in the same package can ac-
cess the member. No other external access is allowed. A member at the package level of ac-
cess cannot be inherited by a derived class in another package. Up to this point, we’ve given
only examples in which every member of a class is inherited by a subclass. With the intro-
duction of the package level of access, we see that Java also lets us selectively restrict the
members that are inherited.
A derived class in the same package retains access to the members of its superclass
that are at the package level of access. All classes within the same package have access to
each other’s public,protected, and package members.
Here’s the preceding example, but with both classes in the same package and someIntat
the package level of access. In this case, both assignment statements are valid.
packageone;
public classSomeClass
{
int someInt;
}
packageone;
public classDerivedClass extendsSomeClass