Click to See Complete Forum and Search --> : Inheritence and getClass problems.


CrazyGaz
04-25-2007, 07:13 PM
Hi there,

I have a couple classes. Room and LockedRoom which is an extension of (and therefore inherits from) Room.

My code is

private void goRoom(String direction)
{
text = "";
Room nextRoom = curRoom.currentRoom.getExit(direction);
if (nextRoom.getClass().getName() == "LockedRoom")
{
LockedRoom nextRoom2 = curRoom.currentRoom.getExit(direction);
if (nextRoom2.returnLocked() == true)
{
text += "The Room is locked.";
}
}


I cannot get the Class without defining it as a room first. However it should only try to define nextRoom2 if it is a LockedRoom, but when I try to run this, it says "incompatible types - found Room but Expected LockedRoom.

Cheers,
Gaz.

agent_x91
05-01-2007, 05:05 PM
I don't understand exactly what you're trying to do here... what do you mean you can't get the class without defining it as a room first?

By the way, two quick corrections in your code just to make your life a lil easier ;)

1) You should never compare Strings or any other objects with the == operator, always use obj1.equals(obj2)

2) In an if statement, you don't need to check if something is equal to true or not. Just take off the == true part and it functions in exactly the same way.

potterd64
05-03-2007, 08:05 PM
not sure what you are trying to do, but have you tried using instanceOf?

instead of
if (nextRoom.getClass().getName() == "LockedRoom")

try
if (nextRoom instanceOf LockedRoom)

(I think that's the syntax, should be close)