protected confusion

lyallex_at_nospam.yahoo.co.uk
Date: 05/31/04


Date: Mon, 31 May 2004 12:29:58 +0000 (UTC)

I have the following class in the package test.pack1

package test.pack1;

public class ClassInPack1 {
    
    protected int intInClassInPack1 = 6;
    
    protected class ClassInPack1InnerClass{
        public String getMessage(){
            return("A message from ClassInPack1InnerClass");
        }
    }
}

I can extend this class with another in the same package as follows

package test.pack1;

public class Class1Extender extends ClassInPack1{
    
    public int getIntInClassInPack1(){
        return intInClassInPack1;
    }
    
    public String getMessage(){
        return new ClassInPack1InnerClass().getMessage();
    }
    
    public static void main(String[] args){
        Class1Extender extender = new Class1Extender();
        System.out.println(extender.getIntInClassInPack1());
        System.out.println(extender.getMessage());
    }
}

The output is

6
A message from ClassInPack1InnerClass

If I try to extend this class with a class in a different package

package test.pack2;

import test.pack1.*;

public class Class1Extender extends ClassInPack1{
    
    public int getIntInClassInPack1(){
        return intInClassInPack1;
    }
    
    public String getMessage(){
        //compile fails here
        return new ClassInPack1InnerClass().getMessage();
    }
    
    public static void main(String[] args){
        Class1Extender extender = new Class1Extender();
        System.out.println(extender.getIntInClassInPack1());
        System.out.println(extender.getMessage());
    }
}

The class won't compile.
I can access intInClassInPack1 no problem at all
but if I try to compile I get the message
test/pack2/Class1Extender.java [12:1] ClassInPack1InnerClass() has
protected access in test.pack1.ClassInPack1.ClassInPack1InnerClass
        return new ClassInPack1InnerClass().getMessage();
               ^
1 error

If I had not used any access modifier in ClassInPack1 I would have
package visibility of the members in
ClassInPack1 and I could understand why test.pack2.Class1Extender
would not compile
As it is I have protected access so I would have thought that I could
extend ClassInPack1 in any
package and have access to any protected member regardless of package.
I can get hold of the int but not the Inner class.
If I change the access modifier of ClassInPack1InnerClass to public
everything works fine.
Can anyone explain why this is ?

many thanks

Lyall