Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

Declaration and scoping

 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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 wasn't selected to go to mars. This tiny ad got in ahead of me:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic