嘗試獲取子級字段獲取父級字段時。在此示例中,當創建新的DarkRoom
時,int零將傳遞給DarkRoom
構造函數。它應該將零int分配給thisRoomNumber
字段。下一步 - 創建Tenant
並傳遞我們初始化的一個對象DarkRoom
。由於某種原因Semaphore
類nextRoom
具有字段thisRoomNumber
從Room
繼承和價值96
儘管事實我們指定爲零。什麼不見了?爲什麼我不能從nextRoom.thisRoomNumber
得到0
設計是相當複雜的,也許有一個更簡單的解決方案?獲取父級字段值而不是應該覆蓋父級的子字段
public abstract class Room {
public int thisRoomNumber = 96;
}
主要方法:
public class TestCase {
public static void main(String[] args) {
Room s[] = new Room[1];
{
s[0] = new DarkRoom(0, s);
}
new Tenant("Joe", s[0], s);
}
}
暗房類:
public class DarkRoom extends Room {
private Room thisRoomType = this;
public int thisRoomNumber;
private Room[] rooms;
private Semaphore semaphore= new Semaphore();
@Override
void leave(Tenant t) {
semaphore.release(thisRoomType, rooms, t);
}
public int thisRoomNumber;
public DarkRoom(int i, Room[] s) {
this.thisRoomNumber = i;
this.rooms = s;
}
}
Semaphore類:
public class Semaphore {
public synchronized void release(Room thisRoom, Room[] allRooms, Tenant t) {
Room nextRoom;
while(j < allRooms.length &&
allRooms[j].negativeCounter == 0 &&
thisRoom.getClass().equals(allRooms[j].getClass())){
j++;
}
nextRoom = allRooms[j];
System.out.println(nextRoom.getClass().getName() +"' "+nextRoom.thisRoomNumber);
我會從隱藏的文件* thisRoomNumber *裏面(並且只在裏面)得到零* DarkRoom *嗎? –
沒錯,如果你有這樣的定義兩次。我認爲你的意思是隻在父類中定義一次。 –