Java Reference
In-Depth Information
The definition of the subclass is typically placed in a separate file. Recall that the name
of the file must be the same as the name of the class, and the file extension must be
java
.
The
private
membersofaclassare
private
to the class and cannot be directly
accessed outside the class. Only methods of that class can access the
private
members
directly. As discussed previously, the subclass cannot access the
private
members of
the superclass directly. However, sometimes it may be necessary for a subclass to access
a
private
member of a superclass. If you make a
private
member
public
,then
anyone can access that member. Recall that the members of a class are classified into
three categories:
public
,
private
,and
protected
. So, if a member of a superclass
needs to be (directly) accessed in a subclass and yet still prevent its direct access outside
the class, such as in a user program, you must declare that member using the modifier
protected
. Thus, the accessibility of a
protected
member of a class falls between
public
and
private
. A subclass can directly access the
protected
member of a superclass.
To summarize, if a member of a superclass needs to be accessed directly (only) by a
subclass, that member is declared using the modifier
protected
.
Example 10-4 illustrates how the methods of a subclass can directly access a
protected
member of the superclass.
EXAMPLE 10-4
1
0
Consider the following definitions of the
class
es
BClass
and
DClass
:
public class
BClass
{
protected char
bCh;
private double
bX;
//Default constructor
public
BClass()
{
bCh = '*';
bX = 0.0;
}
//Constructor with parameters
public
BClass(
char
ch,
double
u)
{
bCh = ch;
bX = u;
}
Search WWH ::
Custom Search