Roman Rutkowski
Roman Rutkowski

Reputation: 87

Calling instance method without specifying instance name

I have Two Classes - Chatroom and User.

Chatroom has a function to remove a specified user from the Chatrooms array list.

public void removeUser(User u)
{
    if(userlist.contains(u)){
        userlist.remove(u);
    }
}

And in the class User there is a method called leaveRoom. This method forwards the User parameter to the removeUser method of the instance of Chatroom.

public void leaveRoom(final Chatroom name)
{
    name.removeUser(this);
}

However, it requires for the instance name of the Chatroom class to be given to the function as parameter. Working with blueJ I have to put type this into the window when calling the method from the instance of User.

Now I have been wondering if there is a way to call the right method in the right instance of Chatroom WITHOUT having to specify the instance name as a parameter?

EDIT:

A user can only be in one chatroom at a time. The goal is to leaveRoom() the current chatroom without having to specify it.

Upvotes: 0

Views: 144

Answers (1)

Eran
Eran

Reputation: 393886

If the User instance has only one Chatroom they can be in, you could keep a reference to that Chatroom in the User class, and then you wouldn't have to supply any parameter to leaveRoom.

However, if a User can be simultaneously in multiple Chatrooms, the leaveRoom method must be told which room to leave, so the parameter would be necessary.

If the User can only be in one room at a time, the code can look like this:

public class User {

...
    private ChatRoom currentRoom;
...
    public void leaveRoom()
    {  
        if (currentRoom != null) {
            currentRoom.removeUser(this);
            currentRoom = null;
        }
    }
....
}

Upvotes: 1

Related Questions