• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

Crazy protected modifier: K&B book lies?

Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.

Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic