I can access a protected field outside of class in java

This question already has an answer here:

  • In Java, difference between package private, public, protected, and private 26 answers

  • 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


    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.


    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.

    链接地址: http://www.djcxy.com/p/24074.html

    上一篇: Java中受保护的引用

    下一篇: 我可以在java的类之外访问受保护的字段