Java Reference
In-Depth Information
public
A
(
String
named
)
{
name
=
named
;
}
public
String
getName
()
{
return
name
;
}
}
Here's the definition for
B
:
package
javanut6
.
ch03
.
different
;
import
javanut6.ch03.A
;
public
class
B
extends
A
{
public
B
(
String
named
)
{
super
(
named
);
}
@Override
public
String
getName
()
{
return
"B: "
+
name
;
}
}
Java packages do not “nest,” so
javanut6.ch03.different
is
just a different package than
javanut6.ch03
; it is not con‐
tained inside it or related to it in any way.
However, if we try to add this new method to
B
, we will get a compilation error,
because instances of
B
do not have access to arbitary instances of
A
:
public
String
examine
(
A
a
)
{
return
"B sees: "
+
a
.
name
;
}
If we change the method to this:
public
String
examine
(
B
b
)
{
return
"B sees another B: "
+
b
.
name
;
}
then the compiler is happy, because instances of the same exact type can always see
each other's
protected
fields. Of course, if
B
was in the same package as
A
then any
instance of
B
could read any protected field of any instance of
A
because
protected
fields are visible to every class in the same package.