在尝试让子类字段获取父字段时。在此示例中,当创建 new 时DarkRoom
,会将 int 零传递给DarkRoom
构造函数。它应该将零 int 分配给thisRoomNumber
字段。下一步 - 创建Tenant
并传递一个DarkRoom
我们初始化的对象。出于某种原因,尽管我们分配了零Semaphore
,但类中的nextRoom
has 字段thisRoomNumber
继承自Room
并具有值。什么不见了?为什么我不能从中得到设计相当复杂,也许有更简单的解决方案?96
0
nextRoom.thisRoomNumber
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;
}
}
信号量类:
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);