• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Protected access via inheritance.

 
Ranch Hand
Posts: 430
Android VI Editor Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I thought i understood the protected access modifier but this test kind of confused me a bit.

The following class is in /home/delDir/Person.java


And this class in the home directory i.e. /home/ZiggyTest2.java


Running ZiggyTest2 produces the following error



I thought that i am accessing it using inheritance, i.e. using an instance of '"SmallPerson".
The way i understood it before is that i wont be able to access 'x' using an instance of 'Person' but if using a subclass of Person it should work. Why is this not the case in the above example?

 
Ranch Hand
Posts: 179
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
SmallPerson has indeed access to protected members of its superclass Person via inheritance. But that's not what you're doing here - you are trying to access a protected member inside SmallPerson, from outside the class (ie: from ZiggyTest2) - and since ZiggyTest2 is not a subclass of Person, it cannot access the protected member.

In order to access the inherited member using inheritance, you would have to write something like this:



Now you have a public method in SmallPerson which is accessible to any other class, which via inheritance accesses the protected inherited variable x.

// Andreas
 
O. Ziggy
Ranch Hand
Posts: 430
Android VI Editor Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh so it can only be accessed directly using the class inheriting the parent. Got it. Thanks..
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic