lundi 16 novembre 2020

What is a good practice to get the correct return class with inheritance?

I have different types of users, all of them inheriting from a parent class User:

class User(string username, string password){...}

class UserAdmin(string username, string password) extends User{
   ...
   // new methods
}

class User(string username, string password) extends User{
   ...
   // new methods
}

I have a method to login, but the thing is that if I login with the credentials of a UserAdmin I want to return a UserAdmin, same things for all the other child classes of User.

public User login(String userName, String password) {
    for (User user : usersList) {
        if (user.isCorrectLogin(userName, password)) {
            return user;
        }
    }
    throw new RuntimeException("Login failed !");
}

How can I do that? Should I have multiple login() methods for each types of Users? Or is there a different way to design the users to not have this issue in the first place?

Aucun commentaire:

Enregistrer un commentaire