Omitting public modifier in java methods

This question already has an answer here:

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

  • For the sake of this explanation, the terms "functions" and "methods" are used interchangably. There is a small difference between them, for more information, ask Google.

    Methods in Java that do not explicitly specify a modifier are by default package-private , so the method is visible to all the classes in the same package as the class where the method is declared.

    Public functions are callable by all classes that have access to the class (ie your whole project) and private methods are only callable within the class the method was written in. There is also the protected modifier, which specifies that the functions can only be accessed by the class, all its subclasses and classes in the same package.

    "Why is that important?" , you may ask. Good question!

    You should use modifiers to hide methods/properties from other classes which may ab(use) them or in a bad case could lead to unexpected behaviour (not necessarily technically, but semantically... some methods just need a little more privacy just like we do). So a good place to start is private , which means only the class it is declared in is able to call it. More often than not, you'll need to give other classes access to methods, which is why the package-private , protected and public modifiers exist.

    Data encapsulation is an important paradigm in programming, and these modifiers help you achieve just that.

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

    上一篇: 保护访问类型

    下一篇: 在java方法中省略public修饰符