• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

What is the difference between protected and friendly access specifier.

 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Protected data and methods are accessible to all the classes within the same package and to all the subclasses of any package. Now if this holds true, why the following prog. failed to compile.

 
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The protected members in the superclass are accesseble to the subclasses only through inheritance in another words you can not use the super class reference in the subclass to access the protected members.
The above code will choke at

a.i = a.i * 2;

 
Ritu Kapoor
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But when I change the second class as follows the code compiles.
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Basically Protected members are accessible by subclass of another package only by inheritance and not by Reference of its superclass...

so here in first case you are using the super class reference to access its variable which is not permitted whereas in second case you are accessing by the subclass reference which actually has its copy of variable in it...so its allowed...its nothing but telling the compiler "am accessing my own variable and not the superclass variable"

hope you got it..
 
Aaaaaand ... we're on the march. Stylin. Get with it tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic