1

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.