0

I'm having a hard time understanding the semantics of the construction of the line

PrintWriter out = response.getWriter()

Firstly, I noticed that HTTPServletResponse is an interface, but does not have the method getWriter.

So how is response.getWriter() even possible? Or better yet, how is an interface variable calling a method?? In addition to that, does PrintWriter implement HTTPServletResponse?

I looked through the Java implementation and it doesn't seem to be; then how is it being assigned the response.getWriter()?

Thanks

Dominique
  • 1,080
  • 14
  • 29
dido
  • 3,347
  • 11
  • 34
  • 42
  • HTTPServletResponse inherits the getWriter() method from ServletResponse (by extending this interface). The key to understanding this piece of code is that the container passes an instance of HTTPServletResponse (i.e. some class implementing that interface) to the servlet. – Gyro Gearless Aug 21 '13 at 15:35
  • I tried to re-create this functionality using my own methods but keep getting NullPointer Exception on the arguments part. What kind of instance gets passed in to the HTTPServletResponse? How does that class relate to the interfaces and PrintWriter class? – dido Aug 21 '13 at 19:27

2 Answers2

2

response.getWriter() returns an instance of a PrintWriter.

The method getWriter() is defined on the interface ServletResponse, which is the parent interface of HttpServletResponse.

You have a concrete implementation of an HttpServletResponse which implements the getWriter() method.

You should look at the javadoc for HttpServletResponse.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
1

Does PrintWriter implement HTTPServletResponse

No. HttpServletResponse doesn't have a getWriter method but it is defined in the ServletResponse super interface, more specifically here: ServletResponse#getWriter.

how is an interface variable calling a method?

For example, in your doGet method of your servlet, you receive a HttpServletResponse parameter that the application server sends with an instance of a class that implements this interface. Note that the class implementation can vary through vendors i.e. the class implementation in Tomcat is not the same as one in WebLogic. This is done so you can focus on the main job through the usage of interfaces instead of worring writing different logic for different application server implementations.

Related to the last point:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332