Java - 包私有类内的方法可访问性?
如果我有一个包私有的java类(用“类”声明,而不是“公共类”),那么里面的方法声明为公共或受保护或包私有实际上没有区别,对吗?那么我应该使用哪个,或者什么时候应该使用哪个?我有点困惑。
If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right? So which should I use, or when should I use which? I'm a bit confused.
好吧,也许不会立即。但是,如果您随后(或将来)声明一个从包私有类继承的“受保护”或“公共”类,则原始类成员的可见性确实很重要。
正如 @kmccoy 指出的,将类声明为 Final 消除了子类的可能性。
但这实际上只是装饰门面。如果您随后决定确实需要创建子类,则只需删除
final
...然后您就回到了访问修饰符的选择确实很重要的情况。IMO,底线是你应该选择最合适的修饰符......即使现在没有必要。如果不出意外,您选择的修饰符应该记录您对抽象边界所在位置的意图。
Well maybe not immediately. But if you then (or in the future) declare a 'protected' or 'public' class that inherits from the package-private class, then the visibility of the members of the original class do matter.
As @kmccoy points out, declaring the class as final removes the possibility of subclasses.
But this is really only window-dressing. If you then decide that you really need to create subclasses, you simply remove the
final
... and then you are back in the situation where the choice of access modifiers does matter.IMO, the bottom line is that you should pick the most appropriate modifiers ... even if it is not necessary right now. If nothing else, your choice of modifiers should document your intent as to where the abstraction boundaries lie.