Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Protected - access modifier

 
Kamil Wojcik
Ranch Hand
Posts: 78
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have one problem in understand one thing about protected modifier, here examples:




When I add static to variable x in the first class everything is fine, why? I don't get it.
Thanks for help!


Source: SCJP K. Sierra, B. Bates
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is because If you mark it static then you dont need a reference to access it.
 
anand-k jha
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A protected member can not access through instance of superclass, which is in another package.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do pp.x and x is a static member of pp's class (Parent) this is interpreted by the compiler as Parent.x. Notice that you still have the access control restrictions imposed by the protected access modifier. That means that when a member is both static and protected, it can be accessed by any class in the same package as the class where the member is declared, and in any subclass of the class where the member is declared. Like Abhi said, in this case you don't need an instance of the superclass to access the member, because the member is static (remember that pp.x is just notation for Parent.x.)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic