Protected vs Public in terms of Inheritance in Java

This question already has an answer here:

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

  • You should follow the Principle of Least Privilege.

    This means that members should be assigned the minimum accessibility needed for the program to work.

    If an unrelated class needs access, make it public . Typically this is done only for methods that provide managed access to data.

    If the subclass is to be completely trusted in manipulating the data, and it needs it to work properly, you can make the member protected .

    Else, make it private , so no other class can access it (without going through other more accessible methods that help encapsulate the data).

    If your program works well when it's protected , then do not make it public . Consider making it private , with protected methods that access it, to encapsulate the data better.


    Recall what those access modifiers are doing.

    public fields are fields that any class that uses this class can modify.

    protected fields are fields that the class, its child classes, and classes in the same package can access.

    There is greater risk involved in changing the visibility of those fields, depending on what it is your data is encapsulating. I would strongly recommend against those sorts of declarations.


    Use protected in a superclass only if you want your variable or method to be accessed or overridden by a subclass of that superclass but you do not want that variable or method to be accessed outside of the superclass or subclass (ie publicly).

    Use public when you want your variable or method to be accessed by any class. Note that you should rarely have public non-final variables or public mutable variables.

    if a program runs without any problems with a Protected access modifier set is there any need to change it to Public?

    No, use the least accessible access modifiers for your variables and methods. Therefore if they are not required as public, do not make them public and only make them protected if they are required to be protected (ie required by subclasses). Otherwise make them private.

    For the reasoning behind this, see the section "Item 13: Minimize the accessibility of classes and members" in Effective Java by Joshua Bloch: http://uet.vnu.edu.vn/~chauttm/e-books/java/Effective.Java.2nd.Edition.May.2008.3000th.Release.pdf

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

    上一篇: 默认情况下,枚举中变量的访问级别是多少?

    下一篇: 在Java中继承保护与公共