Avoid type casting for subclasses
Solution 1:
One option is to use generics:
public abstract class UserManager<T extends UserService> {
protected final T userService;
public UserManager(T userService) {
this.userService = userService;
}
}
public class ServerUserManager extends UserManager<ServerUserService> {
public ServerUserManager(ServerUserService userService) {
super(userService);
}
public void someMethod() {
userService.doSomethingForSERVERONLY();
}
}
Solution 2:
I'm not entirely clear what you are trying to achieve but I will suggest in general to try and use design patterns according to your use case.
This one seems similar to a "Strategy Pattern". You have a context (UserManager) that should get some specific strategy (UserService) and use it.
For example:
public interface UserService {
public void execute();
}
public class ServerUserService implements UserService {
public void execute(){
//does something for server
};
}
class ServerUserManager {
private UserService userService;
public ServerUserManager(UserService userService) {
this.userService = userService;
}
public void doSomething() {
return this.userService.execute();
}
};
You can google "Strategy Pattern" to see different flavours of implementation