Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Crazy protected modifier: K&B book lies?

 
Marcin Skrzek
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Sujittt Tripathyrr
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic