I was studying cloning and it lead me to understand protected access better:-
here is the code which i don't understand
Second class that will be importing package one
I know that second class won't compile because of the line o1.method() since it has protected access but then why super.method() is able to call that method when it is protected ?
I hope my question is clear.
The Java Language Specification puts it as
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
So super.method1() is fine, as you're calling it from within the same object. But you can only call method1() from outside the object if you're in the same package.
budsy remo wrote:Could you please explain what do you mean by code that is responsible for the implementation of that object ?
I must admit, I don't find that a very clear statement (it's just quoted from the specification). What it means is, as I said, you can access it from within the same object.
So, you've got a class A. You've got another class B that extends A. An instance of B can access protected members of A on itself. But it can't access those members on a separate instance of A.
Obj o1=new Obj();
but if we use super.method we would succeed .
both of them are trying to do the same thing but why does o1.method() fails and super.method() doesn't ?
by using the super keyword, compiler identifies the protected method of another class is available in current class as the method has being inherited in current class
also the compiler will not allow to referance an object from another class which has Protected access. Use same class referance and call method() it is possible as the Obj class is inherited.