简体   繁体   中英

Parent class accessing protected members of subclasses Java

I have the following code which I think is not totally explained by Oracle's tutorials.

package visibilidad;

import otropaquete.*;

public class ejemplo2 extends Test {
    protected int prot = 4;
}



package otropaquete;

import visibilidad.*;

public class Test {
    public void metodopublico() {
        ejemplo2 a = new ejemplo2();
        System.out.println(a.prot);
        Hija b = new Hija();
        System.out.println(b.prot);
    }
}

class Hija extends Test {
    protected int prot = 3;
}

Basically, what I'm trying to do is to access a protected member of subclasses from the parent class. The funny thing is that this gives a compile time error when the subclass is defined in another package and it runs perfectly if the subclass is defined in the same class.

I would like to know if this behaviour is considered in the standard or not.

The docs are very explicit: protected fields are accessible in the Class, Package and Subclass level. Since the parent is neither a subclass nor inside the same package - the field is not accessible and you're getting a compilation error.

The access-levels table from Oracle docs:

               Access Levels
Modifier    Class   Package Subclass    World
public      Y       Y       Y           Y
protected   Y       Y       Y           N
no modifier Y       Y       N           N
private     Y       N       N           N

In Java there are 4 different access modifiers:

(No Modifier) - Visible to the package.

(private) - Visible to the class only.

(public) - Visible to the world.

(protected) - Visible to the package and all subclasses.

Here is a reference

Using the protected modifier means only other classes of that package and subclasses can access the field/method. In your case the class from the same package works fine and the one from a different package throws compile time error which is exactly what is supposed to happen.

The protected modifier allows access from the same package as well. See the documentation .

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