• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
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.
 
this llama doesn't want your drama, he just wants this tiny ad for his mama
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic