Skip to content
Advertisement

Java create method in Interface and change the parameter type

How do I create an interface that when Overridden can have different types? Sometimes I would like the method to accept an item of type ‘HtmlPage’ and other times I would like it to take the type ‘Document’. Later these could change to even more types.

Example:

JavaScript

I am thinking something like this should be achievable. I have tried looking around using keywords ‘Overload’ and ‘Override’ in my searches but cannot find something that can work like this. As you can see ‘MyClass’ has Overridden the method and has defined the parameters being used.

Advertisement

Answer

It feels that you are trying to force the code to solve a problem that you don’t understand clearly. I like to step back and think about the connections between components and improve my design in such situations.

Maybe think along the lines that an HtmlPage is a Document. So, if you extend an HtmlPage with a Document (public class HtmlPage extends Document). When an Interface method accepts Document, it will take HtmlPage. Assuming that you have control over the relationship between Document and HtmlPage, in other words, you are not using a third-party library. Once that is done, a method won’t need to operate on two unrelated concepts.

I’ am not clear about the definition of your problem, better naming might have helped, either way, a potential solution might look like this:

JavaScript

https://docs.oracle.com/javase/tutorial/java/generics/types.html

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement