Java - 包含变量的抽象类? [英] Java - Abstract class to contain variables?
问题描述
是否是抽象类定义实例变量的好习惯?
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();
}
然后,子类ExternalJavaScript.class会自动获取源变量,如果所有的子类本身定义了源代码,而不是继承,我觉得阅读代码更容易。
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.
您的建议是什么?
/ 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;
}
把这个问题带回来, / setter代码是什么时候读的?如果他们都做得到和设置,那么你不需要担心在读代码时该函数'做什么。
还有一些其他原因需要考虑:
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:
- 如果源被保护(可以通过子类访问)凌乱:谁在改变变量?
- 如果你的getter / setter方法没有获取和设置,那么描述一个对象,当你需要重构时,它变得很难,而方法会使这个步骤更容易。
总是认为你的类是不是真的不同的东西,这应该有助于决定你是否需要什么更多
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
这篇关于Java - 包含变量的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!