I’m trying to implement a private message system. Let me know if this is bad design but I have two classes User and Recipient. Recipient is a User so it inherits User. Recipient has additional properties like messageId, readDate, keepMessage.
My code is as follows:
//This line gives me ClassCastException
recipient = (Recipient) user;
.
//GET id of user to send message to
String receiverId = request.getParameter("id");
//GET title of message
String title = request.getParameter("title");
//Get content of message
String content = request.getParameter("content");
//Retrieve logged in user from session
HttpSession session = request.getSession();
User sender = (User) session.getAttribute("user");
//Instantiate a new User to hold receiver
User user = new User();
//Retrieve object of user to send message to
UserService userService = new UserService();
user = userService.getUserById(Integer.valueOf(receiverId));
//Instantiate a new Recipient (extends User)
Recipient recipient = new Recipient();
//Cast User as a Recipient
recipient = (Recipient) user;
//Instantiate a message
Message message = new Message();
//message related stuff here....
//Pass the message content and Recipient to messageService
MessageService messageService = new MessageService();
messageService.sendPrivateMessage(message, recipient);
You cannot really do that with Java. Based on what you said above you cannot cast a Recipient to a User. Do you really need to do this though? In the instance above it looks like you should be able to just instantiate it as a Recipient.