5

I was checking the Servlet API and I noticed that GenericServlet is an abstract class that implements the javax.servlet.Servet interface. I was wondering why the authors of GenericServlet class declared an abstract method "service(ServletRequest req, ServletResponse res)" if this method is already declared in the interface javax.servlet.Servlet. Any idea?

Bravo
  • 59
  • 2
  • 5
    It's unlikely that `javax.servlet.Servlet` will ever provide a default implementation for `service()`, but if they do, `GenericServlet` subclasses will still be forced to provide their own. That's the only practical difference between not implementing a method at all and marking it explicitly as abstract. – biziclop Jul 02 '15 at 14:04
  • 2
    Another possible reason is to enable the use of the `@Override` annotation in Java 5, when it was only allowed for methods inherited from superclasses, not for methods implemented from interfaces. – biziclop Jul 02 '15 at 14:10
  • 5
    Nice guess, @biziclop, but that method was already there in Servlet 2.1 (Nov 1998) far before Java 5 (Sep 2004). Possibly even earlier, but no documentation exist for pre-Servlet 2.1. The only ones who can reasonably answer this are the original authors of the Servlet specification. If I should guess, my best guess would be it being just a little oversight. – BalusC Jul 04 '15 at 06:38
  • 1
    @BalusC I wouldn't have thought this was the real reason either but it's fun to hunt for possible differences. The difference in behaviour when a default method is added is actually quite useful to know, it'd make a good test question for one of those annoying interview tests that don't really test your abilities. :) – biziclop Jul 04 '15 at 10:47

1 Answers1

1

Generic Servlet is abstract class and implements both javax.servlet.Servlet and javax.servlet.ServletConfig interface. This class implements Servlet interface, it provides default implementation of all the methods available in Servlet and ServletConfig interface. service() method is still abstract in GenericServlet which means any servlet extending Generic Servlet has to provide implementation of service() method. Because this method is the main method where complete logic of your servlet goes and how can a generic servlet knows which logic to execute. If this method is not abstract then developers might leave this method unimplemented.

Zia
  • 1,001
  • 1
  • 13
  • 25