File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Protected access via inheritance.

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • 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?

 
Andreas Svenkson
Ranch Hand
Posts: 179
  • 0
  • Mark post as helpful
  • send pies
  • 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 Debian VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh so it can only be accessed directly using the class inheriting the parent. Got it. Thanks..
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic