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:

public interface MyInterface{
   void checkThis() throws Exception;

   Output Show(Input input, String url) throws Exception;
}

public class HeadLevel extends MyInterface<HtmlPage,String>{
   Output scrape(HtmlPage page, String url) throws Exception;
}

public class MyClass implements HeadLevel<Output>{
   @Override 
   public void checkThis(Document page, String url){

   }
}

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:

interface MyInterface{
    <K extends Document> void checkThis(K htmlPage) throws Exception;

    Output Show(Input input, String url) throws Exception;
}

class HeadLevel implements MyInterface{
    public <K extends Document> void checkThis(K htmlPage) throws Exception
    {
        // Do something
    }

    public Output Show(Input input, String url) throws Exception{
        return new Output();
    }

    public <K extends Document> Output scrape(K htmlPage, String url) throws Exception
    {
        return new Output();
    }
}

class MyClass extends HeadLevel{

    public MyClass() throws Exception
    {
        checkThis(new HtmlPage());
        checkThis(new Document());
    }

    public <K extends Document> void checkThis(K htmlPage) throws Exception
    {
        super.checkThis(htmlPage);
    }
}

class Document{

}

class HtmlPage extends Document
{

}

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

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