Abstract method with different parameters Java

Ninja Dude :
public abstract class CommonClass {

      abstract void send(<what should i put here???>) {}
    }   

 public class ClassA extends CommonClass {

      void send(List<Comments> commentsList) {
            // do stuff
      }
    }

 public class ClassB extends CommonClass {

      void send(List<Post> postList) {
            // do stuff
      }
    }

I am new to OODP, I am trying to have a method that is able to take in any kind of List data so that I can abstract things out. How can i do this?

Elliott Frisch :

You could make it generic on some type T. Like,

public abstract class CommonClass<T> {
    abstract void send(List<T> al);
}   

And then, to implement it - use the generic. Like,

public class ClassA extends CommonClass<Comments> {
    @Override
    void send(List<Comments> commentsList) {
        // do stuff
    }
}

public class ClassB extends CommonClass<Post> {
    @Override
    void send(List<Post> postList) {
        // do stuff
    }
}

Also, as discussed in the comments, your class names could be improved to be more intuitive; something like,

public abstract class AbstractSender<T> {
    abstract void send(List<T> al);
}

and then

public class CommentSender extends AbstractSender<Comment> {
    @Override
    void send(List<Comment> commentsList) {
        // do stuff
    }
}

public class PostSender extends AbstractSender<Post> {
    @Override
    void send(List<Post> postList) {
        // do stuff
    }
}

That has the advantage(s) of being more readable and easier to reason about (I can tell what a PostSender does by reading the name, ClassB not so much).

Finally, this looks like a case where an interface would work since your abstract class is purely virtual (and should be preferred since you can implement multiple interface, but can only extend from a single parent class);

public interface ISender<T> {
   void send(List<T> al);
}

public class CommentSender implements ISender<Comment> {
    @Override
    void send(List<Comment> commentsList) {
        // do stuff
    }
}

public class PostSender implements ISender<Post> {
    @Override
    void send(List<Post> postList) {
        // do stuff
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138987&siteId=1