I currently am working on a project where I have 3 user classes, lets say UserA, UserB, UserC, that inherit from a abstract User class.
The program is supposed to emulate a system wish requires users to login and logout.
The instances of those users are stored in 3 separate lists.
Only one user is "logged" at any time, so I have a User currentUser variable.
When I want to call a method specific to UserA, B or C, I do a cast. How can I avoid doing that cast while keeping the code elegant?
Code ex:
public abstract class User { } public class UserA extends User { public void clearAgenda(); } public class UserB extends User { } public class UserC extends User { } public class System { private User loggedUser; public void clearUserAgenda() { ((UserA) loggedUser).clearAgenda(); } } Note: I know before hand that if a operation is being used, the current user supports that operation. (ex: if System.clearUserAgenda() is called then the user is a instance of UserA)
User currentUser, but later want to call a method and know which type of user thiscurrentUseris. How is thecurrentUserstored? And who is responsible for calling methods like theclearUserAgenda(or other methods that may only be called when a particular type of user is thecurrentUser)? That is, how does the caller know which type of user is currently logged in?Userinterface thatSystemcalls. Something sufficient vague, likedoWork()orprocessRequest(). Then theUserAimplementation would callclearAgenda(), and the other implementations would do the correct things for those classes.