私人vs保护 - 可见性良好实践关注 [英] Private vs Protected - Visibility Good-Practice Concern

查看:131
本文介绍了私人vs保护 - 可见性良好实践关注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找,我知道理论上的差异。




  • public 可以访问方法/属性。

  • protected - 只有此类和任何子类可以访问方法/属性。 > private - 只有此类可以访问方法/属性。



这很好,问题是,实用他们之间的区别?什么时候使用 private ,什么时候使用 protected



到目前为止,为了保留继承和多态性的概念,我使用 public 用于内部方法(逻辑,辅助方法等)的外部访问(如构造函数和主类功能)和 protected 。我在正确的轨道上吗?



(请注意,这个问题是为了我,但也为未来参考,因为我还没有看到像这样的问题SO)。

解决方案

不,你不在正确的轨道上。一个好的经验法则是:使一切尽可能私密。这使得您的类更加封装,并允许更改类的内部,而不会影响使用您的类的代码。



如果你设计你的类是可继承的,那么仔细选择什么可以重写并从子类访问,并使其受保护(最后,谈论Java,如果你想让它可访问,但不可覆盖)。但请注意,只要您接受您的类的子类,并且有一个受保护的字段或方法,此字段或方法是该类的公共API的一部分,并且以后不能更改,而不会打破子类。



不打算继承的类应该是最终的(在Java中)。你可以放松一些访问规则(私有的保护,最终到非最终)为了单元测试,但然后记录它,并清楚地表明,虽然该方法是受保护的,它不应该被覆盖。 p>

I've been searching and I know the theoretic difference.

  • public - Any class/function may access the method/property.
  • protected - Only this class and any subclasses may access the method/property.
  • private - Only this class may access the method/property. It won't even be inherited.

That's all fine and well, the question is, what's the practical difference between them? When would you use private and when would you use protected? Is there a standard or acceptable good practice over this one?

Up until now, to retain the concept of inheritance and polymorphism, I use public for anything that should be accessed from the outside (like constructors and main class functionality), and protected for internal methods (logic, helper methods etc). Am I on the right track?

(Note that this question is for me, but also for future reference as I haven't seen a question like this one SO).

解决方案

No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.

If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.

A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.

这篇关于私人vs保护 - 可见性良好实践关注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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