简体   繁体   English

Java抽象类-实例变量是私有的还是受保护的?

[英]Java abstract class - Should the instance variables be private or protected?

Should the instance variables be private or protected in java abstract class? 实例变量应该是私有的还是在Java抽象类中受保护的?

Simple question. 简单的问题。 I am trying to get more insight into the concept of abstraction in java. 我试图对Java中的抽象概念有更多的了解。 Thanks! 谢谢!

As a rule of thumb, go for non-final private variables. 根据经验,可以使用非最终私有变量。 If your design calls for giving derived classes access to these variables, provide protected methods for accessing them. 如果您的设计要求让派生类访问这些变量,请提供受保护的方法来访问它们。

Using protected variables creates maintenance liability in all classes, abstract or not. 使用受保护的变量会在所有类(无论是否抽象)中产生维护责任。 As soon as someone inherits from your abstract class, your protected variables become exposed as if they were public. 有人从您的抽象类继承后,您的受保护变量就会像公开一样被公开。 Here are some reasons why this variables should be avoided: 以下是应避免使用此变量的一些原因:

  • Inheriting classes can change your variables at will - this may go around variable validations set up by the abstract base class 继承类可以随意更改变量 -这可能会绕过抽象基类设置的变量验证
  • Inheriting classes become dependent on variable names and types - this locks in the design choice that you made when defining protected variables. 继承类变得依赖于变量名和类型 -这将锁定您在定义受保护变量时所做的设计选择。

First rule does not apply to final variables because they cannot be changed, so they the rule makes an exception for them. 第一条规则不适用于最终变量,因为它们无法更改,因此它们对该规则来说是一个例外。 Second rule still applies, though, so you should be careful about defining protected variables even in case that they are final. 但是,第二条规则仍然适用,因此即使在定义变量为最终变量的情况下,也应谨慎定义。

If protected then this class and any subclasses may access the property. 如果受保护,则此类和任何子类都可以访问该属性。 If private then only this class may access the property (it is not inherited). 如果为private,则只有此类可以访问该属性(不继承)。 It depends on if you need to access them in any subclass. 这取决于您是否需要在任何子类中访问它们。

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

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