简体   繁体   English

Java抽象类:受保护的字段或公共集/获取方法

[英]Java abstract class: protected fields or public set/get methods

If I got an abstract class that I'm intended on creating sub classes from, is it better practice to have the fields in the abstract class to be protected or have the sub classes use setters and getters instead? 如果我有一个抽象类,我打算从中创建子类,那么更好的做法是让抽象类中的字段受到保护,或者让子类使用setter和getters吗? Are there any pros and cons? 有利有弊吗?

For instance: 例如:

public abstract class MyAbstractClass {
    // option A
    protected int myProtectedInt;

    // option B
    private int myPrivateInt;
    public void setMyPrivateInt() {}
    public int getMyPrivateInt() {}
}

public class MySubClass extends MyAbstractClass {
    // etc
}

Well, it's in part subjective (depends on the scenario) and part preference. 嗯,这部分是主观的(取决于场景)和部分偏好。 I personally never open the fields even to the children classes. 我个人从来没有打开田地甚至是儿童班。 Preferring private fields with protected (or public, as needed) getters and setters have helped me a great deal in the past. 在过去,优先考虑受保护(或公共,根据需要)的私人领域的getter和setter帮助了我很多。 While it adds a few more characters to code, and makes the code look a little less intuitive, I can list a few pros of my preferred approach that may convince you to start using getters/setters with private fields: 虽然它为代码增加了一些字符,并使代码看起来不那么直观,但我可以列出一些我喜欢的方法的优点,可能会说服你开始使用私有字段的getter / setter:

  1. Better control: The parent class knows exactly what changed and what was accessed. 更好的控制:父类确切地知道改变了什么以及访问了什么。 Instead of a child class (or grand child) directly modifying the fields, they have to use the setters, giving the parent class the visibility that might come handy some day 他们必须使用setter,而不是直接修改字段的子类(或大孩子),为父类提供可能在某一天可能派上用场的可见性

  2. Better flexibility: the parent class has the flexibility to change how the fields are maintained, possibly calculated or even refactores significantly without imoacting any of the children classes as long as the signatures of the getter/setters are preserved. 更好的灵活性:只要保留了getter / setter的签名,父类就可以灵活地改变字段的维护方式,可能计算甚至重构,而不会影响任何子类。

  3. Logging, data access and validations: the getter/setter methods can have programmatic logic to log or check for the data type or perform validations before or after the access or modification. 记录,数据访问和验证:getter / setter方法可以具有编程逻辑,用于在访问或修改之前或之后记录或检查数据类型或执行验证。 You may be able to add business logic to ensure the caller has access to reading or writing to the fields. 您可以添加业务逻辑以确保调用者有权读取或写入字段。

  4. Better description: methods can be documented better (JavaDocs of methods can be made much more explanatory than the same of the member variables) 更好的描述:方法可以更好地记录(JavaDocs的方法可以比成员变量的更多解释)

Hope this helps. 希望这可以帮助。

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

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