Win a copy of Rust Web Development this week in the Other Languages 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

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..
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic