This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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?
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.