Search code examples
javatypescastingpolymorphismmessage

How to apply polymorphism in this object


I have the following class

class Message{
    private List content;
    private String messageType;

    public Message(String messageType, List content){
       this.content = content;
       this.messageType = messageType;
    }
}

Okey, now imagine i want to send different message types. For example, the message type "friends". I want to store their ID number (int for example) as a key to find their names (String). That reminds me that i should use the HashMap class. Or a simple String, whatever. And other more cases where i need to use other object types.

The main question here is: how i should proceed here to code a class that have two attributes:

  • The first stores the type of the message
  • The second is the content itself, which should be able to be any kind of object

I have read that casting is a bad practice, so i dont want to declare content as an object and then, cast it in function of the message type.

My thoughts:

  • Declare message as an abstract class and then implement subclasses in function of the message type. What i dont get here is that if i declare an abstract method like getContent() in Message class, i need to stablish the data type that it returns, what get me back to the main issue. This way get useless since i need to send the Message and not the subclass.

Solution

  • You don't need messageType at all, you can just define a generic type with class and use it in content, e.g.:

    class Message<T> {
        private List<T> content;
    
        public Message(List<T> content){
            this.content = content;
        }
    }
    

    Now, let's say if the type is String, you can do:

    Message<String> message = new Message<>(new ArrayList<String>());
    

    This way, you can instantiate Message class with different types. Here is the documentation on generic class types.