java - 为什么我可以使用接口(interface)枚举方法而不覆盖它们?

标签 java jsp interface

我创建了一个 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 的具体实现(LinkedListStack 等)而不更改其类型(List)。

关于java - 为什么我可以使用接口(interface)枚举方法而不覆盖它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43467955/

相关文章:

JSON 对象的 JavaScript 问题

c# - 无法从用法中推断方法 'xyz' 的类型参数

interface - 键盘隐藏我的 UITableViewController 中的文本字段, View 不滚动

html - 浏览器中的链接 href 无效?

javascript - Vue.js 组件在 jsp 文件中不起作用

api - 使用 PC 控制飞利浦 Living Colors

java - 需要使用公钥和 SOAP 消息正文创建签名

java - 如何在html页面中传递数据库结果集值

java - 刷新 ArrayList Android 应用程序

java - 将 jedis 与 spring 一起使用,但不与 spring-data lib 一起使用,在哪里存储池?