This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected access question

 
Mark Redmond
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, could someone please help me with this question from the Sybex study guide?

Code is as follows:

<blockquote>code:
<pre name="code" class="java">
package birdpack;
public class Bird {
protected int nFeathers;
}
</pre>
</blockquote>

and

<blockquote>code:
<pre name="code" class="java">
package duckpack;
import birdpack.Bird;
class Duck3 extends Bird {
Duck3() {
Bird b = new Bird();
b.nFeathers=32;
}
}

</pre>
</blockquote>

When I attempt to compile the subclass I get:

nFeathers has protected access in birdpack.Bird
b.nFeathers=32;



I don't understand why. I should be able to access the protected features of the superclass as I am in a subclass.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mark,

Welcome to JavaRanch!

The rules are actually a little more subtle. Outside its package, a subclass can access its superclass's protected features only through a reference that is "at least" its own type. Therefore Duck3 can access nFeathers in an instance of Duck3, or in an instance of SomeSubclassOfDuck3, but not in an instance of Bird or ChickenSubclassOfBird.

So protected access doesn't give you license to mess with other classes; only the class you're actually writing.
 
Mark Redmond
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it, thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic