Java Reference
In-Depth Information
5. public class RotaryPhone extends Phone {
6. private int number;
7.
8. public RotaryPhone(int n, int e, String r) {
9. super(n, e, r);
10. this.number = super.number;
11. }
12.
13. public void placeCall(int numberToDial) {
14. super.placeCall(numberToDial);
15. System.out.println(“Using ring tone “ + ringTone);
16. }
17. }
The
RotaryPhone
class makes some valid and invalid attempts at accessing the members
of
Phone
:
Line 9 invokes the
protected
constructor of
Phone
, which is valid because
RotaryPhone
is a child of
Phone
.
Line 10 is valid because the
number
field in
Phone
is
public
and therefore accessible to
any other class.
Line 14 does not compile because the
placeCall
method has default access and
RotaryPhone
is not in the same package as
Phone
.
Line 15 does not compile because
ringTone
is
private
in
Phone
and therefore not
accessible outside of the
Phone
class.
Attempting to compile
RotaryPhone
generates the following compiler errors:
RotaryPhone.java:14: placeCall(int) is not public in
com.sybex.demos.Phone; cannot be accessed from outside package
super.placeCall(numberToDial);
^
RotaryPhone.java:15: ringTone has private access in
com.sybex.demos.Phone
System.out.println(“Using ring tone “ + ringTone);
^
2 errors
In the real world you would implement tight encapsulation, so the
number
field of
Phone
would not be
public
. However, the
Phone
class is meant
to demonstrate the effect of the access modifiers, and you can expect
exam questions that contain classes like
Phone
that do not follow good OO
design but instead are testing your knowledge of a specific Java concept.
Search WWH ::
Custom Search