Java default access level (package private access)

2019-07-23 21:00发布

问题:

This question already has an answer here:

  • Pros and cons of package private classes in Java? 8 answers

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.