• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected access question

 
Mark Redmond
Greenhorn
Posts: 7
  • 0
  • 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: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it, thank you
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic