PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 12, 2022

[FIXED] How to apply polymorphism in this object

 July 12, 2022     casting, java, message, polymorphism, types     No comments   

Issue

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.



Answered By - Darshan Mehta
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing