2

Ok so I thought the point of having protected fields was so that the variable was accessible by only the subclass and the class having the protected fields. Making objects of either the subclass or the superclass should not grant access to these fields. If I am correct, how come code like this is compiling correctly?

//superclass
public class SuperClass{
    protected int x = 5;

}

//main class with main method
public class MainClass{        
     public static void main(String[] args) {

         SuperClass a = new SuperClass();

         a.x = 8;       

         System.out.println(a.a);


      }
}

This will print out 8, which means I modified a protected variable outside of the classes which have them...

741236987
  • 59
  • 1
  • 2

3 Answers3

3

protected variables and methods are accessible from other classes of the same package as well as subclasses of the current class.

private variables and method are only accessible from within the current class.

If there is no modifier (none of protected, private or public), then by default the variable is accessible from any classes within the same package but not from subclasses.

see here for the official documentation

Yibin Lin
  • 681
  • 1
  • 6
  • 20
1

protected members in Java are also visible to other classes in the package.

Move your main() method to a different package and you'll get an error.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
-2

I thought the point of having protected fields was so that the variable was accessible by only the subclass and the class having the protected fields.

You thought wrongly.

Making objects of either the subclass or the superclass should not grant access to these fields.

It does. NB You are now contradicting your own thought here. Your thought includes the subclass, and now you're trying to exclude it.

If I am correct

You aren't.

user207421
  • 305,947
  • 44
  • 307
  • 483