This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
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 can not be accessed in derived ??

 
JigaR Parekh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why protected can not be accessed in derived class.



Select 1 correct option.

a It will print 10.
b It will print 20.
c It will not compile.
d It will throw an exception at Run time.
e None of the above

I have selected answer b but correct answer is c why ???
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Protected access can be tricky. You can only access protected members from within the context of the inherited class. For instance, you can access B's 'i' variable (inherited from A), but not A's through an A reference, since B is in a separate package.

From the JLS:

�6.6.2 Details on protected Access
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

Hope this helps!
 
JigaR Parekh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx for explanation
 
Smitha Ballikar
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

I didnt understand the explanation. Can somebody explain why answer is not 20.

Cheers
Smitha
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is not 20, as the B class is not allowed access to A's i variable. It's outside the package, and the code that attempts to access the i variable is not responsible for the implementation of the A type.
 
Ryan Kade
Ranch Hand
Posts: 69
 
Smitha Ballikar
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!! Got it now..
 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks parekh ...

nice question


thanks & regards

srikanth reddy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic