• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

clarification - protected access rules

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been studying to take the 5.0 Programmer's exam using the Sybex Complete Java 2 Certification Study Guide, and I need some clarification. The book states (on multiple occassions) that an instance of a subclass can't access protected inherited fields or other instances. Therefore Line 4 of Derived.java below is illegal

Base.java
1 package bp;
2 public class Base{
3 protected int i;
4 }

and in Derived.java:
1 package dp;
2 public class Derived extends bp.Base{
3 void foo(){
4 System.out.println((new Derived()).i);
5 }
6 }

But, using Eclipse v3.1.2, the above code compiles (as well as runs if I insert a main(), instantiate Derived and call foo()) using the JRE 5.0 compiler. Am I missing something or is the book wrong (is is my compiler wrong!)?

Thanks for any help.
 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can access the protected instance members through inheritance,
i.e using the derived class instance.
 
Ranch Hand
Posts: 243
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The protected members of a superclass can certainly be inherited by the subclass instance.

Nikhil
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What the book perhaps wanted to say is, that you can not use the protected variable of the superclass, when you have an instance.
When in line 4 is written
new Base().i
then, it won't compile.
    Bookmark Topic Watch Topic
  • New Topic