Mazzola Mazzola - 1 year ago 76
Java Question

Java interfaces in jar archives

I'm studying

and I was looking at a fully working example created by my professor. The
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" );

In the above example
uses a
object, so I went into my
servlet-api .jar
, searched for
and found out that
is an interface (
public abstract interface javax.servlet.ServletResponse
) . So in my code I use an object of type
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

So my questions are:

  • Why does compiler let me instantiate an interface?

  • why don't we use a ServletResponseWrapper object?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download