简体   繁体   English

包私有类中的公共成员

[英]Public members in package private class

I wonder if it's okay (not considered bad practice) to have public members in package private class.我想知道在包私有类中拥有公共成员是否可以(不被认为是不好的做法)。 I tend to add public keyword to members of my default visibility classes to indicate that such members are part of the classes API.我倾向于为我的默认可见性类的成员添加public关键字,以表明这些成员是类 API 的一部分。

I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (ie package visibility).我这样做只是为了可读性,因为在这种情况下,公共成员与没有任何访问修饰符的成员具有基本相同的可见性(即包可见性)。 Is that correct?那是对的吗?

Example:例子:

class ModuleImplementationClass {
    private int fieldA;
    private String fieldB;

    private void someClassInternalMethod() {
         // impl
    }

    public int doSth() {
        // method that will be called by other classes in the package
    }
}

I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (ie package visibility).我这样做只是为了可读性,因为在这种情况下,公共成员与没有任何访问修饰符的成员具有基本相同的可见性(即包可见性)。 Is that correct?那是对的吗?

Well that depends.那要看情况了。 Not if you're overriding existing methods (eg toString() ) or implementing an interface.如果您要覆盖现有方法(例如toString() )或实现接口,则不会。

If you don't want the method to be used from outside the package, make it package private.如果您不希望从包外部使用该方法,请将其设为包私有。 If you're happy for it to be used from anywhere, make it public.如果您愿意在任何地方使用它,请将其公开。 Or another way to think about it: design your method access so that if someone changed just the class access to make it a public class, you wouldn't want to change the method access too.或者另一种思考方式:设计您的方法访问权限,以便如果有人仅更改访问权限以使其成为公共类,您也不想更改方法访问权限。

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

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