Question about Protected Modifier

A

AIK

I have the following two classes:

package birdpack;

public class Bird {

Bird() {}

protected int nFeathers;

}

in bird.java

and

package duckpack;
import birdpack.Bird;

public class Duck3 extends Bird {

Duck3() {}

void foo() {
Bird b = new Bird();
int temp;
temp = b.nFeathers;
}

}

in Duck3.java

When I compile Duck3 I get this error: nFeathers has protected access in
birdpack.Bird. Why is this? I thought the point of a protected modifier is
to allow children of a class to access parent's protected feature even if
the child class is in a different package?
 
C

Chris Smith

AIK said:
When I compile Duck3 I get this error: nFeathers has protected access in
birdpack.Bird. Why is this? I thought the point of a protected modifier is
to allow children of a class to access parent's protected feature even if
the child class is in a different package?

Protected access allows access to members of the superclass of the same
object, but not of a different object. Otherwise, protected members of
java.lang.Object would be universally visible, which is obviously not
the intent (and, of course, smaller-scale versions of the same would
occur).

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
R

Rogan Dawes

AIK said:
I have the following two classes:

package birdpack;

public class Bird {

Bird() {}

protected int nFeathers;

}

in bird.java

and

package duckpack;
import birdpack.Bird;

public class Duck3 extends Bird {

Duck3() {}

void foo() {
Bird b = new Bird();
int temp;
temp = b.nFeathers;
}

}

in Duck3.java

When I compile Duck3 I get this error: nFeathers has protected access in
birdpack.Bird. Why is this? I thought the point of a protected modifier is
to allow children of a class to access parent's protected feature even if
the child class is in a different package?

Note that in the example above, you are not accessing the "protected
int" of the parent class Bird, you are trying to access the "protected
int" of the new Bird instance that you have instantiated.

Something like:

public class Duck3 extends Bird {

Duck3() {}

void foo() {
System.out.println(nFeathers);
}

}

in Duck3.java would work.

Rogan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top