问题描述
如果我有一个java类是package-private(声明为类,而不是公共类),真的没有区别,如果里面的方法是public或protected或package-private,对不对?那么我应该使用哪个,或什么时候应该使用哪个?我有点困惑。
也许不是立即。但是,如果你(或将来)声明一个继承于package-private类的'protected'或'public'类,那么原始类的成员的可见性 / p>
正如@kmccoy指出,将类声明为final会删除子类的可能性。
但这只是一个窗口。如果你确定你真的需要创建子类,你只需删除 final
...然后你回到访问修饰符的选择很重要的情况。
IMO,底线是你应该选择最合适的修饰符...即使现在不需要。如果没有别的,你选择的修饰符应该记录你的意图,抽象的边界在哪里。
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.
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.
这篇关于Java - 在package-private类中的方法可访问性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!