简体   繁体   中英

Protected access to members from a subclass of the subclass

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?

如果BA的子类,并且CB的子类,则C也是A的子类,并且可以访问Aprotected成员。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM