David Jirovec
David Jirovec

Reputation: 98

Java - protected access modifier

I have these classes:

package abc;

public class A {

    public int publicInt;
    private int privateInt;
    protected int protectedInt;
    int defaultInt;

    public void test() {
        publicInt = 0;
        privateInt = 0;
        protectedInt = 0;
        defaultInt = 0;
    }

}

"A" contains attributes of all four access modifiers. These other classes extend "A" or create instances and try to access attributes.

package de;

public class D {

    public void test() {
        E e = new E();
        e.publicInt = 0;
        e.privateInt = 0; // error, cannot access
        e.protectedInt = 0; // error, cannot access
        e.defaultInt = 0; // error, cannot access
    }

}

package de;

import abc.A;

public class E extends A {

    public void test() {
        publicInt = 0;
        privateInt = 0; // error, cannot access
        protectedInt = 0; // ok
        defaultInt = 0; // error, cannot access
    }

}

package abc;

import de.E;

public class C {

    public void test() {
        E e = new E();
        e.publicInt = 0;
        e.privateInt = 0; // error, cannot access
        e.protectedInt = 0; // ok, but why?
        e.defaultInt = 0; // error, cannot access
    }

}

Everything is ok, except I do not understand, why in class C, I can access e.protectedInt.

Upvotes: 1

Views: 216

Answers (3)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

I think a code illustration would help here to understand better.

Add a protected member in Class E

public class E extends A {
    protected int protectedIntE;
    ...

Now, try accessing it in Class C

e.protectedInt = 0; // ok, but why?
e.protectedIntE = 0; // error, exactly as you expected

So, the thing to note here is that although you accessed protectedInt through an instance of E it actually belongs to Class A and was just inherited by Class E through inheritance. An actual (non inherited) protected member of Class E is still not accessible like you expected.

Now, since Class A and Class C are in the same package and protected access basically works as a superset of package (by including sub-class access as well) compiler had nothing to complain here.

Upvotes: 1

zeyorama
zeyorama

Reputation: 445

Acces Control

Follow the link, you get to the java documentation, explanes the modifier accessibalities.

protected classes, function, etc. are visible for your current class, package and subpackages. Also visible inside subclasses of your class.

Upvotes: 0

David M
David M

Reputation: 72870

Because C is in the same package as A (package abc), and the protected modifier in Java includes access within the same package.

Upvotes: 1

Related Questions