Mazzola Mazzola - 1 month ago 6
Java Question

Java interfaces in jar archives

I'm studying

servlets
and I was looking at a fully working example created by my professor. The
service()
method of my servlet looks like this:

public void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.setContentType( "text/plain");
PrintWriter out = res.getWriter();

out.println( "Some response" );
out.close();
}


In the above example
service()
uses a
ServletResponse
object, so I went into my
servlet-api .jar
, searched for
javax.servlet.ServletResponse.class
and found out that
ServletResponse.class
is an interface (
public abstract interface javax.servlet.ServletResponse
) . So in my code I use an object of type
ServletResponse
which is an interface, but I thought that you could not instantiate an interface in Java. I also noticed that this interface is implemented by
ServletResponseWrapper.class
.

So my questions are:


  • Why does compiler let me instantiate an interface?

  • why don't we use a ServletResponseWrapper object?


Answer

You aren't instantiating the interface ServletResponse. You are using a reference that was passed to you by the servlet container when it calls the service() method on your servlet. The container instantiates a class that implements ServletRepsonse interface. The instantiated (concrete) class could be ServletResponseWrapper or any other "internal" classes as long as it implements the ServletResponse interface.

Try printing res.getClass().getName() in your service() method. It should tell you the exact class name that's being instantiated by the servlet container.