Java Reference
In-Depth Information
Access control and inheritance
The Java specification states that:
• A subclass inherits all the instance fields and instance methods of its superclass
accessible to it.
• If the subclass is defined in the same package as the superclass, it inherits all
non- private instance fields and methods.
• If the subclass is defined in a different package, it inherits all protected and
public instance fields and methods.
private fields and methods are never inherited; neither are class fields or class
methods.
• Constructors are not inherited (instead, they are chained, as described earlier
in this chapter).
m
g
O
However, some programmers are confused by the statement that a subclass does not
inherit the inaccessible fields and methods of its superclass. It could be taken to
imply that when you create an instance of a subclass, no memory is allocated for any
private fields defined by the superclass. This is not the intent of the statement,
however.
Every instance of a subclass does, in fact, include a complete
instance of the superclass within it, including all inaccessible
fields and methods.
This existence of potentially inaccessible members seems to be in conflict with the
statement that the members of a class are always accessible within the body of the
class. To clear up this confusion, we define “inherited members” to mean those
superclass members that are accessible.
Then the correct statement about member accessibility is: “All inherited members
and all members defined in this class are accessible.” An alternative way of saying
this is:
• A class inherits all instance fields and instance methods (but not constructors)
of its superclass.
• The body of a class can always access all the fields and methods it declares
itself. It can also access the accessible fields and members it inherits from its
superclass.
Member access summary
We summarize the member access rules in Table 3-1 .
Search WWH ::




Custom Search