• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

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.
 
get schwifty. tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!