Java default access level (package private access)

2019-07-23 20:51发布

This question already has an answer here:

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?

3条回答
孤傲高冷的网名
2楼-- · 2019-07-23 21:12

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.

查看更多
闹够了就滚
3楼-- · 2019-07-23 21:26

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.

查看更多
混吃等死
4楼-- · 2019-07-23 21:34

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...
    }
}
查看更多
登录 后发表回答