• 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:

Declaration and scoping

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All, I got this question from enthuware mock test:




variable "i" is declare as protected. how can class B cannot access "i"? please help. :roll:

regards,
Edmen
 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Edmen, protected members can be accessed in the sub-class only through inheritance. You cannot use an instance of the sub-class to access it( i.e. you cannot use dot operator to access it).
Here the value i is accessed without the . operator. So compiles and runs fine.
Hope, this helps.
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Abhi vijay wrote:Edmen, protected members can be accessed in the sub-class only through inheritance. You cannot use an instance of the sub-class to access it( i.e. you cannot use dot operator to access it).



You can use an instance of the subclass to access it, as protected member is now existing in subclass through inheritence.
The trick is you cannot use an instance of the superclass to access it, think protected as private member if accessed outside the package.

If you use
B b=new B();
b.i; then there is no problem.

If you use
A a=new A();
a.i; outside the package of A than i will not be visible outside the package.
 
I will open the floodgates of his own worst nightmare! All in a 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