公共成员在包private类中 [英] Public members in package private class

查看:145
本文介绍了公共成员在包private类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以(不是坏习惯)在包私有类中有公共成员。我倾向于添加 public 关键字到我的默认可见性类的成员,以表明这些成员是类API的一部分。

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.

我只是为了可读性,因为在这种情况下,公共成员与没有任何访问修饰符(即包可见性)的成员具有基本相同的可见性。是否正确?

I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?

示例:

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 (i.e. package visibility). Is that correct?

这取决于。如果你正在覆盖现有的方法(例如 toString())或实现一个接口,则不会。

Well that depends. Not if you're overriding existing methods (e.g. toString()) or implementing an interface.

不想让该方法从包外部使用,使其包私有。如果你喜欢它从任何地方使用,使其公开。或者以另一种方式来思考:设计你的方法访问,如果有人改变只是访问使其成为一个公共类,你不会想改变方法访问。

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.

这篇关于公共成员在包private类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆