Java - Method accessibility inside package-private class?

自古美人都是妖i 提交于 2019-12-30 08:12:53

问题


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.


回答1:


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?

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.




回答2:


Public methods inside a package class are public to classes in the same package. But, private methods will not be accessible by classes in the same package.



来源:https://stackoverflow.com/questions/1350171/java-method-accessibility-inside-package-private-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!