Java Reference
In-Depth Information
used by the program:
class Test extends points.Point {
public static void main(String[] args) {
Test t = new Test();
t.print();
}
protected void print() {
System.out.println("Test");
}
}
then these classes compile and
Test
executes to produce the output:
Test
If the method
print
in class
Point
is changed to be
public
, and then only the
Point
class
is recompiled, and then executed with the previously existing binary for
Test
, then no
linkage error occurs. This happens even though it is improper, at compile time, for
a
public
method to be overridden by a
protected
method (as shown by the fact that the
class
Test
could not be recompiled using this new
Point
class unless
print
in
Test
were
changed to be
public
.)
Allowing superclasses to change
protected
methods to be
public
without breaking binaries
of pre-existing subclasses helps make binaries less fragile. The alternative, where such a
change would cause a linkage error, would create additional binary incompatibilities.
13.4.8. Field Declarations
Widely distributed programs should not expose any fields to their clients. Apart from the
binary compatibility issues discussed below, this is generally good software engineering
practice. Adding a field to a class may break compatibility with pre-existing binaries that
are not recompiled.
Assume a reference to a field
f
with qualifying type
T
. Assume further that
f
is in fact an
instance (respectively
static
) field declared in a superclass of
T
,
S
, and that the type of
f
is
X
.
If a new field of type
X
with the same name as
f
is added to a subclass of
S
that is a super-
class of
T
or
T
itself, then a linkage error may occur. Such a linkage error will occur only
if, in addition to the above, either one of the following conditions hold:
• The new field is less accessible than the old one.
• The new field is a
static
(respectively instance) field.