Hi guys, I seem to be having some problems understanding access.
I've got some code taken from the OCA book and made some change to it.
The code as it is doesn't compile, because apparently this line generates an error. Now, Gosling extends Bird and they sit in a different package, so I don't have package private access, but floatInWater() is of access protected so I would have thought that because Gosling extends Bird I could create an object of type Bird inside Gosling and access that protected method even from another package (if I change the access modifier of floatInWater() to public the code runs. I thought that the point of a protected access was to allow access from a subclass regardless of package
Most of the time, subclasses access protected fields/methods via the this reference, so, this issue rarely comes up (and this is why line 7 works) .... but ... in order to access a protected field, your class need to be responsible of the implementation.
This means that the reference needs to be of a type, that IS-A the class, where the code accessing the class, is located.
Right, I gave it a read, not sure I understood the whole thing though. I guess I'm a bit confused because I'm creating an object of a different class, different than the one inside which I'm declaring the object, that is
what I meant was it's probably the fact that in class Gosling I'm trying to create an object of type Bird, and because Gosling extends Bird I thought I could access its protected method even if they sit inside the same package. I'm not too sure I understand that responsible for implementation requirement in practice
Jason Attin wrote: I'm not too sure I understand that responsible for implementation requirement in practice
Let me try to elaborate a bit...
First of all, where is the code that is accessing the protected field? Well, in this case, it is a static method of the Gosling class. To be specific, it is the main() method of the Gosling class.
So, the "code" is part of the Gosling class. The "responsible for the implementation" rule states that it is allowed to access all protected fields of super classes, provided that it too are IS-A Gosling instances. This means that, if you had done this in the main() method...
it works. Notice that you are still accessing the super class protected field, but in this case, the reference IS-A Gosling instance, and this "code" is responsible for Gosling instances, so hence, this would be allowed.
In other words, you can access super class protected fields (that are declared in classes in different packages), it is just that the reference must be IS-A Gosling; so, the object type must be Gosling class type or one of its sub class types.