接口中的Java创建方法并更改参数类型

时间:2016-07-11 18:42:06

标签: java parameters overloading override

如何创建一个Overridden可以有不同类型的界面?有时我希望该方法接受“HtmlPage”类型的项目,有时我希望它采用“文档”类型。后来这些可能会变成更多类型。

示例:

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){

   }
}

我认为这样的事情应该是可以实现的。我在我的搜索中尝试使用关键字“重载”和“覆盖”,但找不到可以像这样工作的东西。正如您所看到的,'MyClass'已重写方法并定义了正在使用的参数。

2 个答案:

答案 0 :(得分:0)

In this case you don't need any interface, it's not possible to do what you want, you need to understand the concept of interfaces before use it.

https://docs.oracle.com/javase/tutorial/java/concepts/interface.html

答案 1 :(得分:0)

The implementation I was looking for turned out to not exist however there is a better way to be able to do what I was looking for using Input and Output.

public interface MyInterface<Input, Output> {
   void checkThis(Input input, Output output) 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){

   }
}

It seems the answer was actually under my nose. I misunderstood what Input/Output types are and how you can use them. Input and Output can be of any time that you expect to come in or go out of an application sort of speak.

Input is any information that is needed by your program to complete its execution.There are many forms that program input may take

Input can take the form of many different types such as HtmlPage, Document, and String. Using input you can Override your method and have your desired types.

You can read more about Input and Output here