0

Suppose following class Structure:

inside namespace a

public abstract class A {

    protected int someVal;
    protected abstract int action();

}

in namespace a.b

public class B extends A{

    //magically filled with elements ;)
    List<A> elements; 

    protected int action(){
        someVal = 42; // OK
        int l = 0;
        for (A a : elements){
            l+= a.action(); //FORBIDDEN!!
        }
        return l;
    }
}

so Eclipse suggests me to

Change the visibility of 'action' to 'protected'

I feel some kind of fooled.

Why I'm allowed to implement action, but not to call it? I have no problem accessing someVal either.

I'm well aware of copying B into the same namespace, but I have many Classes which extend B or similiar C's and D's etc. and like to have them in order.

Or to rephrase my Question: Is this packet 'thingy' the only way to force my classes to have a protected method, but hide that from client code?

4

1 回答 1

2

From a static typing perspective a may not be an instance of B. You can't touch the protecteds of a non-descendent class (except via the same package get out). protected should be used rarely, if at all.

于 2013-01-19T02:53:56.813 回答