简体   繁体   中英

public static methods in class with only package visiblility?

Is there a problem if I make all static methods public in a class with only package visibility? I do not want the methods to be accessible outside the package unless I change the class visibility to be public, in which case I do want them all to be visible without having to individually make them public.

Will making all static methods public while not making the class public satisfy the requirements above?

Update/Clarification: As a clarification, the static methods are factory methods so I want them available to anybody who can see the class. That's why I want to keep them at maximal visibility (instead of minimal visibility as commonly suggested) so that they are visible to whoever can see the class. And when the class visibility expands I do not have to hunt and find the static methods to change their visibility too. I want a single flip switch.

Yes. This is a normal use case for access modifiers. There is nothing wrong with having public methods in a class with package visibility.

However, 'all' static methods need not be kept public. You should still use private and protected methods for tasks which are internal/implementation specific.

The idea is to keep the accessibility as minimal as possible at first, and then expose them when required. By 'Accessability to minimum' i mean only the combined effect. As long as the effect is same it doesn't matter how it is achieved. The only other consideration is rework... when you eventually make this class public, do you want these methods to be visible? If yes, you better keep the methods public.

Note that for static methods 'effect is the same'. However for instance methods, a subclass would be able to provide access to the public method in a package-level class. So in that case the effect would not be the same.

通常,作为设计原则,任何方法或实例变量的访问修饰符都应具有相同或较窄的可见性(访问修饰符)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM