Reputation: 11
I am preparing for the SJCP 6, and I found a detail I had not seen so far for accessing a protected member from a subclass of the subclass for the class where the member is declared. I am clear that a protected member can only be accessed from another package when we try to access it through inheritance, but what about a subclass of the subclass, can we still access it?
The book says:
Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass.
My question is about the subclasses of the subclass, how those see the member, as protected also? Can they access it? Because it says the member becomes private to any code outside the subclass, with the exception of subclasses of the subclass, so, how do they see it?
Upvotes: 1
Views: 1306
Reputation: 4609
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package and also by subclass of subclasses or any class within the package of the protected members' class. i just created an example in eclipse for this case go and try it .. For eg
Class MyClass in package test have a method protected named get method
package test;
public class MyStaticClass {
protected int getmethod(){
int a=0;
return a;
}
}
Class A in same package extends MystaticClass and the protected method is accessible there
package test;
public class A extends MyStaticClass{
@Override
protected int getmethod() {
// TODO Auto-generated method stub
return super.getmethod();
}
}
Now class B extending A which is in another package can also access the same method
package testing;
import test.A;
public class B extends A{
@Override
protected int getmethod() {
// TODO Auto-generated method stub
return super.getmethod();
}
}
Now class c extending B again in another package also can access it.. package testinggg;
import testing.B;
public class c extends B{
@Override
protected int getmethod() {
// TODO Auto-generated method stub
return super.getmethod();
}
}
So it is accessible in subclasses of sublclasses in another package
Upvotes: 0
Reputation: 59185
If B
is a subclass of A
, and C
is a subclass of B
, then C
is also a subclass of A
and has access to A
's protected
members.
Upvotes: 2