简体   繁体   English

PHP和Java:将属性的可见性设置为私有,并通过派生类的过度杀手来访问它吗?

[英]PHP & Java: Is setting property's visibility private and accessing it via getter from derived class overkill?

So what do you think? 所以你怎么看?

My Java lecturer said that properties should always be declared private and there is no reason why it should be done any other way. 我的Java讲师说,应始终将属性声明为私有,并且没有理由以其他任何方式进行设置。 I immediately started to think inheritance, how it would affect to that. 我立即开始思考继承,它会如何影响。

Do you mean declaring the field to be private? 您的意思是宣布该字段为私有吗? If so, I agree with your lecturer, although "no reason" may be slightly overkill. 如果是这样,我同意你的讲师,虽然“没有理由”可能有点矫枉过正。 There are very occasional reasons to use non-private fields - such as in private nested classes. 偶尔会有使用非私有字段的原因-例如在私有嵌套类中。

But yes, in a simple superclass/subclass relationship I would use getters/setters instead of making the field protected. 但是,是的,在一个简单的超类/子类关系中,我使用getters / setters而不是保护字段。 It separates the implementation from the API exposed by the class - even to its subclasses. 它将实现与类所公开的API分开-甚至对其子类也是如此。

Private would prevent classes that extend the original class from accessing it directly. Private会阻止扩展原始类的类直接访问它。 Generally speaking I think that protected is a better way to declare a variable if you expect to extend your original class and want the inheriting class to be able to directly modify that particular class member. 一般而言,如果您希望扩展原始类并希望继承类能够直接修改该特定类成员,那么我认为保护是声明变量的更好方法。

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

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