1

I noticed strange behaviour of access modifier

package protected_test.pack1;

public class Source {
    protected int protectedInt= 1;    
}

package protected_test.pack2;

import protected_test.pack1.Source;

public class Child extends Source{

    public static void main(String[] args) {
        System.out.println(new Child().protectedInt);//line 1
        System.out.println(new Source().protectedInt);//line 2      
    }
}

line 1 compiles good but line 2 writes The field Source.protectedInt is not visible

Before this I didn't know anything about this difference. Can you provide good explanation of visibility with details ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • Because that's how access modifiers work – MadProgrammer Jul 08 '14 at 07:37
  • The protected keyword allows package access and inheritance access. Line 1 works because the Child class has access to that inherited protected property. Line 2 would only work if the Child class was in the dame package as the Source class. Since it isn't, you get a compilation error. – Dan Temple Jul 08 '14 at 07:37
  • I don't see anything here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – gstackoverflow Jul 08 '14 at 07:46

0 Answers0