This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Access protected member from the class of different package.  RSS feed

 
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have confusion that why can't we access the protected member from the subclass in different package using the parent class reference. i need to know the reason for it.

for example,

In below code why can't we access the protected variable 'x' using the parent class (Parent) reference.




 
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mihir,

The protected access specifier requires that the protected member is visible in a subclass outside the package only as inherited member of the subclass.
So


works absolutely fine.....

However when you are using the Parent reference, the member varriable x is being accessed as an instance varriable of Parent class and not as a varriable inherited by Child from Parent. So you get the complier error.
 
Marshal
Posts: 59124
180
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch The full details are to be found in the Java™ Language Specification. It's not easy reading, however.
 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot... Jishnu....
 
Mihir Patel
Greenhorn
Posts: 18
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Welcome to the Ranch The full details are to be found in the Java™ Language Specification. It's not easy reading, however.



Thanks Ritchie..
As you said it's not easy to read, but it also really a good stuff to clear my understandin regarding protected member access...

thanks again..
 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are welcome..
 
Campbell Ritchie
Marshal
Posts: 59124
180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

jishnu dasgupta wrote:you are welcome..

Agree
 
You've gotta fight it! Don't give in! Read this tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!