简体   繁体   中英

Getting parent class field value instead of child field which supposed to override parent's

While trying to get child class field getting parent field. In this example, when new DarkRoom is being created the int zero is passed to DarkRoom constructor. It supposed to assign zero int to thisRoomNumber field. The next step- creating Tenant and passing one object DarkRoom which we initialized. For some reason in Semaphore class the nextRoom has field thisRoomNumber which inherited from Room and has value 96 despite the fact we assigned zero . What is missing? Why I cannot get 0 from nextRoom.thisRoomNumber The design is quite complex, maybe there is a bit simpler solution?

public abstract class Room {
public int thisRoomNumber = 96;
}   

Main method:

 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);
        }
    }

DarkRoom class:

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 class:

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);

You are hiding the field thisRoomNumber by declaring it in the subclass as well. Remove the declaration of it in the sub class ( DarkRoom ).

Fields are not polymorphic in Java. Only methods are. Do what every decent book suggests, and never use public fields. Use a getter instead, and override the getter in the subclass. Fields can't be overridden.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM