简体   繁体   中英

Why can I use Interface Enumeration methods without overriding them?

I have created a jsp where I use the interface Enumeration. The jsp works all right, but I don't understand how does my program know how to use both the hasMoreElements() and the nextElement() methods if I haven't overriden them and I don't use a class that overrides them. An interface method is supposed to have no body, right?

<%@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.");}
%>

on the line:

Enumeration e=request.getParameterNames();

getParameterNames of request object returns an implementation of Enumeration interface. As the returned object implements Enumeration it is possible to call methods of this interface in your code.

It is not necessary to know what concrete class instance returns getParameterNames() .

It is enough to know, that the returned result implements Enumeration interface, and it is possible to use Enumeration interface methods with the obtained result.

Moreover, not directly related to your question, it is advised to use interface types in such cases to not stick to concrete class implementations.

For example, it is better to replace this kind of declarations:

ArrayList<String> myList = new ArrayList<>();

to this kind of declarations:

List<String> myList = new ArrayList<>();

It makes your code more flexible and maintainable. You can change concrete implementations of myList ( LinkedList , Stack , etc) without changing its type ( List ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM