【发布时间】:2013-06-20 22:48:28
【问题描述】:
我目前正在制作一个简单的插件程序。我的问题是我不想让插件访问所有基本插件字段/方法。例如:
public abstract class BasePlugin {
private int x; //Mysterious x
public abstract void update(); //update func that may need x, but can't change it
protected final int getX() {return x;} //x accessor
}
除非您意识到无法设置 x,否则这将起作用。
我能做什么?我想让子类(插件)无法更改 x,但让它读取值。在创建时值应该至少可以访问一次(这就足够了)。
编辑:构造函数在大多数情况下都有效,但如果我有例如:
public abstract class BasePlugin {
private List<int> x; //Mysterious x
public abstract void update(); //update func that may need x, but can't change it
protected final List<int> getX() {return x;} //x accessor
public BasePlugin(List<int> y) {x = y;}
}
public class Plugin {
public Plugin(List<int> y)
{
super(y);
y.remove(0); //Will it work?
}
}
【问题讨论】:
-
有什么问题?那行得通
-
您希望它在施工时设置吗?如果是这样,这很容易解决。
-
我无法以任何方式设置 X。或者我只是不知道怎么做。
-
@MichaelMyers 将其设置在构造中就足够了,正如我所说的(创建时一次)。
标签: java class inheritance superclass