I`m just prepearing to SCJP 5.0 and there is strange thing with class memeber having protected modifier. Look at this:
------file aa/A.java----- package aa; public class A { protected int i; }
-----file bb/B.java----- package bb; import aa.A; public class B extends A {}
----file aa/OtherClass.java---- package aa; import bb.B; public class OtherClass { public static void main(String...args) { A a = new A(); System.out.println(a.i); //OK it`s obvoius B b = new B(); System.out.println(b.i); //OK!!! it`s strange } }
------------------------------ It looks like the sentence on page 36 in K&B book for scjp1.5 is not true:
Once the subclass-outside-the-package inherits the protected member, that member(as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass
So, shouldn`t this sentence finish with:
and with the exception of classes in the same package, where the superclass declaration exists
,should it?
SCJP 5, SCWCD 1.4, SCBCD 5
Sujittt Tripathyrr
Ranch Hand
Joined: Jun 21, 2006
Posts: 96
posted
0
Hi
Here the Class B extends A and A has a protected variable "i".so with B's object we can access the superclass variable.
Here note a point that variable "i" is protected so we can able to call in the same package else it will throw error.