• Post Reply Bookmark Topic Watch Topic
  • New Topic

Protected access outside the package  RSS feed

 
Rajesh Nagaraju
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



when we compile the class Run2 we get compilation errors as
com\jspiders\app2\Run2.java:10: error: i has protected access in D
d1.i = 456;
^
com\jspiders\app2\Run2.java:11: error: print() has protected access in D
d1.print();
^
2 errors

However if we change the class Run2 as follows it compiles.


Can you please explain why D d1 = new Run2() fails to compile and Run2 d1 = new Run2() compiles successfully?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm actually surprised the second one compiles. To be able to access a protected member of a superclass that's not in the same package, you're supposed to have to do it as this.member or super.member. I don't think you're allowed to do arbitrary_subclass_reference.member.

But maybe I'm wrong. Maybe it's just that you have to do it through a subclass reference, not a superclass reference.

Details are here: http://docs.oracle.com/javase/specs/jls/se5.0/html/names.html#6.6.2
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!