File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
 
Similar Threads
Conditional (Ternary) Operator (?:)
Using ID of link as Parameter
EJB QL & heterogeneous relationships
doubt on object
StringBuffer / StringBuilder methods