File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

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/
package aa;
public class A {
protected int i;

-----file bb/
package bb;
import aa.A;
public class B extends A {}

----file aa/
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?

Sujittt Tripathyrr
Ranch Hand

Joined: Jun 21, 2006
Posts: 96

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.

I agree. Here's the link:
subject: Crazy protected modifier: K&B book lies?
It's not a secret anymore!