isn't protected supposed to be accessible only by subclasses in Java?

Viewed 47

I got really surprised that this code didn't get me any compile errors.

class A {
    protected int a;
}
 
class B {
    void b() {
        A a = new A();
        a.a = 4;
    }
}
2 Answers

No, protected is visible to other classes in the same package.

The thing to remember is that access modifiers are meant to keep from bothering OTHERS with too much information. If you are working in the same package, then you’ve already got the information, use it if you want to.

In java protected variable is accessible within the package and outside the package but by use of inheritance. If any other class from outside the package, try to access these variables the compiler will throw an error at compilation time. You can read it detail https://javagoal.com/access-modifiers-in-java/#12

Related