0

Please consider the following code snippet:

import java.io.*;
import java.util.*;
import javax.servlet.*;

public class PostParametersServlet extends GenericServlet{
    public void service(ServletRequest request , ServletResponse response) throws 
         ServletException,  IOException { .... 

and so on and so forth.....

My Question:

It's been said that we cannot create an object of an interface but if we consider the above code snippet, ServletRequest and ServletResponse are the core interfaces of javax.servlet package.

Also, "request" and "response" are said to be objects in the above program description.

Could anyone tell/explain me how can these interfaces have object of their own considering the fact that interfaces cannot have objects?

Please correct me if I'm wrong somewhere.

spajce
  • 7,044
  • 5
  • 29
  • 44
Adarsh
  • 49
  • 8
  • your question is a bit confusing but I *think* what you are missing is that you can refer to an object by its interface. For example if you have an interface Animal and a class Dog you can declare Animal myAnimal = new Dog(). – mconlin Apr 06 '13 at 23:00
  • check this [question](http://stackoverflow.com/questions/3355408/explaining-interfaces-to-students) to learn more about interfaces – A4L Apr 06 '13 at 23:00

3 Answers3

1

Objects implement interfaces. So in the case of ServletRequest, there is an object that implements it, something like this:

public class ServletRequestImpl implements ServletRequest {
    // All of the methods defined in ServletRequest implemented here.
}

When you get the ServletRequest in your service() method, you are really getting a concrete object that implements that interface.

I suspect your confusion is around the fact that interfaces don't have implementation details within the interfaces themselves. Interfaces just provide a specification for other objects to implement.

Todd
  • 30,472
  • 11
  • 81
  • 89
0
Could anyone tell/explain me how can these interfaces have object of their own considering the fact that interfaces cannot have objects?

This is incorrect.

An interface-typed reference can refer to any object that implements that interface.

You'll notice that HttpServletRequest and HttpServletResponse both implement the respective interfaces. You can certainly pass either of those objects here.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Consider following types:

public interface A {
public void m();
}
public class B implements A {
public void m() {
    // TODO Auto-generated method stub  
}
}

Now you can have any code lines:

public static void main(String[] args) {
A a = new B();
anyMethod(a);
}

public static void anyMethod(A a) {
System.out.println(a.getClass());
}

In anyMethod, the parameter type is the interface A, but the real type is B which will be displayed with sysout

miwoe
  • 757
  • 1
  • 6
  • 17