File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Crazy protected modifier: K&B book lies? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Crazy protected modifier: K&B book lies?" Watch "Crazy protected modifier: K&B book lies?" New topic
Author

Crazy protected modifier: K&B book lies?

Marcin Skrzek
Ranch Hand

Joined: Oct 19, 2005
Posts: 38
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
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.

Thanks
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Crazy protected modifier: K&B book lies?
 
Similar Threads
confusion of protected
Modifier protected does not hide inherited members to (static) code of superclass package Query
Modifier protected does not hide inherited members to (static) code of superclass package
Constructor questions:Can constructor be static, synchronized, final,
Possible error in K&B book (resolved - no error)