The Java Program: ProtectedMethod.java
1 class Base {
2
3 private int x=1, y=2, z=3;
4
5 private int getX () { return x; }
6 protected int getY () { return y; }
7 public int getZ () { return z; }
8
9 }
10
11 class Derived extends Base {
12
13 /*
14 Trying "super.getX()" in "Dervied" class results in a compiler error:
15 "getX() has private access"
16 */
17
18 /*
19 A method can be overriden only if it is accessible. If the
20 method is not accessible then it is not inherited, and if it is
21 not inherited it can't be overriden. For example, a private
22 method is not accessible outside its own class. If a subclass
23 defines a method that coincidentally has the same signature and
24 return type as the superclass's private method, they are
25 completely unrelated---the subclass method does not override the
26 superclass's private method.
27 Arnold, et al, The Java Programming Language, 3rd edition, 2000, page 77.
28 */
29
30 public int getX () {return 0;}
31
32 public int getY () {return super.getY();}
33
34 /*
35 Compile-time error: "attempting to assign weaker access privileges"
36
37 private int getZ () {return super.getZ();}
38 protected int getZ () {return super.getZ();}
39 */
40
41 }
42
43 public class ProtectedMethod {
44 public static void main (String[] args) {
45 }
46 }