posted 24 years ago
General Visibility
This question builds directly on Question 1.
Assume we have the following code in the file /abc/def/Q.java:
1: //File: /abc/def/Q.java:
2: package def;
3:
4: public class Q {
5: private int privateVar;
6: int packageVar;
7: protected int protectedVar;
8: public int publicVar;
9: }
and this code is in /abc/Tester.java:
1: //File: /abc/Tester.java:
2: import def.Q;
3:
4: public class Tester extends Q {
5: Q sup = new Q();
6: Sub sub = new Sub();
7:
8: public void someMethod() {
9: // First, try to refer to sup's memebers.
10: sup.privateVar = 1; // Line 10
11: sup.packageVar = 2; // Line 11
12: sup.protectedVar = 3; // Line 12
13: sup.publicVar = 4; // Line 13
14:
15: // Next, try to refer to this object's members
16: // supplied by class Q.
17: privateVar = 5; // Line 17
18: packageVar = 6; // Line 18
19: protectedVar = 7; // Line 19
20: publicVar = 8; // Line 20
21:
22: // Next, let's try to access the members of
23: // another instance of Tester.
24: Tester t = new Tester();
25: t.privateVar = 9; // Line 25
26: t.packageVar = 10; // Line 26
27: t.protectedVar = 11; // Line 27
28: t.publicVar = 12; // Line 28
29:
30: // Finally, try to refer to the members in a
31: // subclass of Tester.
32: sub.privateVar = 13; // Line 32
33: sub.packageVar = 14; // Line 33
34: sub.protectedVar = 15; // Line 34
35: sub.publicVar = 16; // Line 35
36: }
37: }
and this code is in /abc/Sub.java:
1: //File: /abc/Sub.java:
2: public class Sub extends Tester {}
According to the explanation for the above code, line 12 won't compile but line 19 will. Can anyone explain why?