aspose file tools*
The moose likes Beginning Java and the fly likes protected access question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "protected access question" Watch "protected access question" New topic
Author

protected access question

Mark Redmond
Greenhorn

Joined: Jul 10, 2008
Posts: 7
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Mark Redmond
Greenhorn

Joined: Jul 10, 2008
Posts: 7
got it, thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: protected access question