[英]Java call a method before constructor
我有一個Map類,它帶有setMapName方法,可以從Enum mapName中選擇設置它,在構造函數中,有一個規則根據mapName值從數組扇區Alien或Human命名一個單元格,我想測試該單元的名稱確實是Alien或Human,但我為空。
public class Map {
private Name mapName;
private final Sector [][] sector;
private int Matrix [][];
private static final int X=23;
private static final int Y=14;
public Map (){
sector = new Sector[X][Y];
for (int i=0; i < X; i++){
for (int j=0; j<Y; j++) {
sector[i][j] = new Sector (i,j);
}
}
Matrix = new int[23][14];
if(mapName==Name.FERMI){
sector[10][8]=new Alien(10,8);
sector[10][9]=new Human(10,9);
}
if(mapName==Name.GALILEI||mapName==Name.GALVANI){
sector[10][5]=new Alien(10,5);
sector[10][7]=new Human(10,7);
}
}
public int[][] getMatrix() {
return Matrix;
}
public void setMatrix(int matrix[][]) {
Matrix = matrix;
}
public Name getMapName() {
return mapName;
}
public void setMapName(Name mapName) {//this is the method i want to use before the constructor
this.mapName = mapName;
}
public Sector[][] getSectors(){
return sector;
}
public void addSectors(){
Sector.add(sector);
}
}
public enum Name {
FERMI, GALILEI, GALVANI
}
public class MapTest {
@Test
public void testMapAlien(){
Map map = new Map();
map.setMapName(Name.FERMI);
assertEquals(Name.Alien, map.getSectors()[10][8].getSectorName());
}
}
setMapName
是Map
類上的一個非靜態成員函數(由於與java.util.Map
沖突而得名)。 這意味着可以在Map
的現有實例(例如,已經構建的Map
上調用它。
您的問題是在調用構造函數后調用setMapName
,但是您的構造函數需要一個有效的Name
才能正常工作! 這是一個經典的雞肉和雞蛋問題。
為什么不直接將MapName
傳遞給構造函數?
public Map (Name mapName){
sector = new Sector[X][Y];
for (int i=0; i < X; i++){
for (int j=0; j<Y; j++) {
sector[i][j] = new Sector (i,j);
}
}
Matrix = new int[23][14];
if(mapName==Name.FERMI){
sector[10][8]=new Alien(10,8);
sector[10][9]=new Human(10,9);
}
if(mapName==Name.GALILEI||mapName==Name.GALVANI){
sector[10][5]=new Alien(10,5);
sector[10][7]=new Human(10,7);
}
...
}
您的問題是您沒有初始的mapName。 調用構造函數時,mapName為null。 所以...
您可以通過兩種方式做到這一點:
//Constructor with argument mapName
public Map (Name mapName){
setMapName(mapName); //or this.mapName = mapName;
...
}
要么:
//Give a value to mapName on the constructor without arguments, but I recommend the first one to your case.
public Map (){
...
mapName = value;
...
setMapName(mapName);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.