抽象类中字段的可访问性应该是什么? [英] What should the accessablity of Fields in a Abstract Class be?

查看:20
本文介绍了抽象类中字段的可访问性应该是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地举个例子,

public abstract class AbstractFellow {

    protected Thing buddy;
....

public class ConcreteFellow extends AbstractFellow {
     public void someMethod() {
          buddy.doSomething();
          //OR
          buddy = somethingElse;
          //OR
          somethingElse = buddy;
     }
}

这是不好的做法吗?

推荐答案

意见不一.我的观点是,即使在抽象类中,使用私有成员和受保护的访问器(即 protected getBuddy())也是更好的做法.

Opinions vary. My opinion is that even in abstract classes, using private members and protected accessors (i.e. protected getBuddy()) is a better practice.

它允许封装始终允许的相同内容:在超类中包含获取伙伴"对象的逻辑,并允许您在不破坏所有继承类的情况下更改该逻辑.

It allows for the same things encapsulation always allowed: to contain the logic of obtaining the "buddy" object in the super-class, and allowing you to change that logic without breaking all inheriting classes.

超类也可能不希望 buddy 被改变.例如,您可能希望在发生这种情况时取消注册侦听器或进行其他一些清理 - 使用 setter 方法有助于实现这一点.

The super-class might not expect buddy to be changed, either. For example, you might want to unregister listeners or do some other cleanup when that happens - having a setter method helps achieve that.

此外,它显然允许您将 Buddy 作为只读成员(因为您只能提供 getBuddy 而没有 setBuddy),这不是使用成员很容易完成(您始终可以将其设置为 final,但是您也可以防止超类更改它!)

In addition, it obviously allows you to have Buddy as a read-only member (since you can provide only a getBuddy and no setBuddy), something that is not as easy to accomplish with a member (you can always set it to be final, but then you prevent the super-class from changing it, too!)

这篇关于抽象类中字段的可访问性应该是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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