如何在构造函数之外访问 java 中的继承属性?
public PainelPrincipal(Jogo jogo,GridPanel gridPanelPrincipal) {
super(jogo,gridPanelPrincipal);
listaBlocos = new LinkedList<>();
carregarFicheiroNivel();
gridPanelPrincipal.setEventHandler(this);
}
private void carregarFicheiroNivel() {
FileHandler handler = new FileHandler("/niveis/EstadoInicial.txt");
String conteudo = handler.readFile();
String[] colunas = null;
int y=0;
for(String linha: conteudo.split("\n")){
colunas = linha.split(" ");
for(int x = 0; x < colunas.length; x++) {
if(colunas[x].substring(1, 2).equals(PAREDE)){
grelha[x][y] = new Parede();
gridPanelPrincipal.put(0, 0, grelha[0][0].getCellRepresentation());
}else{
switch(colunas[x].substring(0, 1)){
case "0":break;
}
}
}
y++;
}
}
这行 gridPanelPrincipal.put(0, 0, grelha[0][0].getCellRepresentation()); 似乎不起作用,他不认识 gridPanelPrincipal 类构造函数之外的变量。
是否可以在构造函数之外访问它或者我该如何做到这一点?
最佳答案
您无法在构造函数外部访问它,因为它可能是私有(private)
。您只能在构造函数中访问它,因为它是构造函数的参数。
您可以:
- 在父类(super class)中设置适当的变量
protected
,使其对子类可见,或者 - (有点笨拙)在子类中创建您自己的变量来存储它自己对
GridPanel
的引用,以便您可以通过其他方法访问它。
关于java - 继承属性访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23530286/