简体   繁体   English

Java - 包私有类中的方法可访问性?

[英]Java - Method accessibility inside package-private class?

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? 如果我有一个java类,它是package-private(用“class”声明,而不是“public class”),如果里面的方法被声明为public或protected或package-private,那么确实没有区别,对吧? So which should I use, or when should I use which? 那么我应该使用哪种,或者何时应该使用哪种? I'm a bit confused. 我有点困惑。

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? 如果我有一个java类,它是package-private(用“class”声明,而不是“public class”),如果里面的方法被声明为public或protected或package-private,那么确实没有区别,对吧?

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. 正如@kmccoy指出的那样,将类声明为final可以消除子类的可能性。

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. 如果你确定你真的需要创建子类,你只需删除final ......然后你就会回到访问修饰符的选择很重要的情况。

IMO, the bottom line is that you should pick the most appropriate modifiers ... even if it is not necessary right now. IMO,最重要的是你应该选择最合适的修饰符......即使现在没有必要。 If nothing else, your choice of modifiers should document your intent as to where the abstraction boundaries lie. 如果不出意外,您选择的修饰符应记录您对抽象边界所在位置的意图。

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. 但是,同一个包中的类将无法访问私有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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