Java default access level (package private access). Why it is used for? [duplicate]

一世执手 提交于 2019-12-11 02:15:25

问题


Although I know how default (package) access level works in java, I can't imagine its real use in applications except for those with unique package. What do you use default access level for in business (usually multipackage) java applications?


回答1:


A very common pattern for using package-private classes is to create shared implementations of interfaces or shared subclasses of common classes.

Note that the fact of sharing is important here, because inner classes provide a better alternative for hiding class / interface implementations from the caller.

Another common use is for "utility classes", when you wish to share a group of algorithms "horizontally" among different classes, without exposing these algorithms to outside users of your class library. Various argument checkers fall into this category.




回答2:


I would use them when client code doesn't need to know the proper class implementing an interface and initializing it through a factory method or builder because the class by itself can be very complex to handle.

E.g.

Interface

package foo.bar;

public interface FooBarInterface {
}

Implementations of interface

package foo.bar;

class FooImpl implements FooBarInterface {
}

package foo.bar;

class BarImpl implements FooBarInterface {
}

Factory method:

package foo.bar;

public class FooBarInterfaceCreator {
    public static FooBarInterface create(String param) {
        //creates instance based on parameters...
    }
}



回答3:


Mostly I've used that access for unit tests. In which case, I've to change some of my private methods to give them package access, so as to test them. Of course your unit tests should follow same package structure as your actual code.



来源:https://stackoverflow.com/questions/28414803/java-default-access-level-package-private-access-why-it-is-used-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!