java抽象类变量,Java - 包含变量的抽象类?

关于在抽象类中定义实例变量是否是良好实践的讨论。文章指出,虽然这样可以让子类自动获取变量,但可能使代码可读性下降。建议是限制变量访问权限并保持getter/setter的纯粹性,同时考虑类的实际用途来决定是否需要额外的抽象。
摘要由CSDN通过智能技术生成

Is it good practice to let abstract classes define instance variables?

public abstract class ExternalScript extends Script {

String source;

public abstract void setSource(String file);

public abstract String getSource();

}

The sub class, ExternalJavaScript.class, would then automatically get the source variable but I feel it's easier to read the code if all the sub classes themselves define the source, instead of from inheritance.

What is your advice?

/Adam

解决方案

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

private String source;

public void setSource(String file) {

source = file;

}

public String getSource() {

return source;

}

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code.

There are a few other reasons to think about too:

If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.

If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值