Java Reference
In-Depth Information
Let's now write the definition of the method
setData
of the
class
DClass
. Because
bCh
is a
protected
instance variable of the
class
BClass
, it can be directly accessed in
the definition of the method
setData
. However, because
bX
is a
private
instance
variable of the
class
BClass
, the method
setData
of the
class
DClass
cannot directly
access
bX
. Thus, the method
setData
of the
class
DClass
must set
bX
by using the
method
setData
of the
class
BClass
. The definition of the method
setData
of the
class
DClass
can be written as follows:
public void
setData(
char
ch,
double
v,
int
a)
{
super
.setData(v);
bCh = ch;
//initialize bCh using the assignment
//statement
dA = a;
}
Note that the definition of the method
setData
contains the statement:
super
.setData(v);
to call the method
setData
with one parameter (of the superclass), to set the instance
variable
bX
, and then directly set the value of
bCh
.
Next, let's write the definition of the method
toString
(of the
class
DClass
):
public
String toString()
{
return
(
super
.toString() + "Subclass dA = " + dA + '\n');
}
The constructors' definitions are:
1
0
public
DClass()
{
super
();
dA = 0;
}
public
DClass(
char
ch,
double
v,
int
a)
{
super
(ch, v);
dA = a;
}
The following program shows how the objects of
BClass
and
DClass
work:
public class
ProtectedMemberProg
{
public static void
main(String[] args)
{
BClass bObject =
new
BClass();
//Line 1
DClass dObject =
new
DClass();
//Line 2
Search WWH ::
Custom Search