我创建了一个 jsp,我在其中使用了接口(interface) Enumeration。 jsp 工作正常,但我不明白我的程序如何知道如何同时使用 hasMoreElements()
和 nextElement()
方法,如果我没有覆盖它们并且我不使用覆盖它们的类。接口(interface)方法应该没有主体,对吧?
<%@page import="java.util.*"%>
<%
char respuesta;
int g=0; //Gryffindor
int r=0; //Ravenclaw
int h=0; //Hufflepuff
int s=0; //Slytherin
String valorParametro;
Enumeration e=request.getParameterNames();
try {
while (e.hasMoreElements()) {
valorParametro=request.getParameter(e.nextElement().toString());
respuesta=valorParametro.charAt(0);
switch(respuesta) {
case 'A':
out.write("Un punto para Gryffindor...<br>");
g++; break;
case 'B':
out.write("Un punto para Ravenclaw...<br>");
r++; break;
case 'C':
out.write("Un punto para Hufflepuff...<br>");
h++; break;
case 'D':
out.write("Un punto para Slytherin...<br>");
s++; break;
}
}
} catch (Exception ex) {out.write(e.toString());}
out.write("Y tu casa es...");
if (g>r && g>s && g>h) {out.write(" ¡GRYFFINDOR!");}
else if (r>g&&r>s&&r>h) {out.write(" ¡RAVENCLAW!");}
else if (h>g&&h>s&&h>r) {out.write(" ¡HUFFLEPUFF!");}
else if (s>g&&s>r&&s>h) {out.write(" ¡SLYTHERIN!");}
else {out.write(" Chico, el sombrero no sabe qué decir.");}
%>
最佳答案
在线:
Enumeration e=request.getParameterNames();
request
对象的 getParameterNames
返回 Enumeration
接口(interface)的实现。由于返回的对象实现了 Enumeration
可以在您的代码中调用此接口(interface)的方法。
不必知道返回什么具体类实例getParameterNames()
。
只要知道,返回的结果实现了Enumeration
接口(interface),就可以使用Enumeration
接口(interface)方法获取结果。
此外,与您的问题没有直接关系,建议在这种情况下使用接口(interface)类型,不要拘泥于具体的类实现。
例如,最好替换这种声明:
ArrayList<String> myList = new ArrayList<>();
对于这种声明:
List<String> myList = new ArrayList<>();
它使您的代码更加灵活和可维护。您可以更改 myList
的具体实现(LinkedList
、Stack
等)而不更改其类型(List
)。
关于java - 为什么我可以使用接口(interface)枚举方法而不覆盖它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43467955/