wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Protected access via inheritance. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Protected access via inheritance. " Watch "Protected access via inheritance. " New topic
Author

Protected access via inheritance.

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430

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

Joined: Jan 17, 2011
Posts: 179
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

Joined: Oct 02, 2005
Posts: 430

Oh so it can only be accessed directly using the class inheriting the parent. Got it. Thanks..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Protected access via inheritance.
 
Similar Threads
Protected Member Access Problem
Confused on protected modifier
I'm gonna SNAP!
Predict the output
Access protected member from the class of different package.