The use of visibility modifiers in Java

后端 未结 8 2186
谎友^
谎友^ 2021-01-06 01:32
class Orange{

    Orange(){
    }

}

What is the difference between the usage of the modifier - in this case, package-private - in front of the cl

相关标签:
8条回答
  • 2021-01-06 02:22

    I find the best visibility level in Java to be the default visibility i.e. package visibility, because it enables unit test classes to access all the methods, if the test is placed in the same package as the main class.

    Also package visibility is shorter to write since you can omit the visibility declaration, so there is less boiler plate.

    The second best visibility level is protected, since in some cases you can create your test classes as sub-classes of your main class. However, as stated before, package visibility works better in most cases, if you use packages properly.

    Third, typically if you run Sonar and do code review and static analysis on large projects, I have found out that typically 80% of the methods are public, and 20% are private/protected. Thus, the main idea of using private or protected methods is to protect the data/properties from being accessed by bypassing the accessors. Most of the methods will be typically public anyways.

    The most useless visibility level (but unfortunately commonly used) is private as it's impossible to test (without using Reflection and modifying the visibility to something else). Also, private prohibits code re-use in sub-classes, which is the main idea of using object oriented paradigm in the first place, and thus should be avoided. For the same reasons keyword final should be avoided in most cases.

    Thus, I find your example to be the best practice how to define the visibility levels, except that your constructor is not public :). However, you are missing the package declaration and unit tests.

    0 讨论(0)
  • 2021-01-06 02:26

    You can only declare a public or default class (in case of top level classes only) in Java and these modifiers decide the accessiblity of the class.

    I also suggest you to see "Why can't a class or an interface receive private or protected access modifiers?"

    Now as for as constructor concerns, a constructor will have aaccess-control of type default when no access-modifier is defined explicitly. So this constructor will have a Package Level Access. Only those class which are defined within that package as that of the class with this default constructor will be able to access it. See "Aren't Java constructors public by default?"

    If the constructor is made private, then only the code within that class can access this. For a better understanding of modifiers, you need to see "Access Modifiers In Java"

    0 讨论(0)
提交回复
热议问题