HttpServlet hierarchy explanation

2019-08-01 07:19发布

I'm a little concern about some facts of java hierarchy model.

As stated in java tutorials:

an abstract class may not implement methods ( but they can) and if you extend from an abstract class you must implement all methods of superclass otherwise the new class must be abstract as well

But right now, I'm learning servlets classes and found that my servlet runs even if I don´t implement all of the methods declared in HttpServlet, what is happening? I see that in the source they are protected methods (dopost, doget ,etc) and even it says compiled code) but even if they are protected how we can extend the methods to create new servlets, is it because the public abstract HTTPservlet signature? .

I also found this very unusual, what's the meaning?

  private static final
    String METHOD_DELETE = "DELETE";
    private static final
String METHOD_HEAD = "HEAD";
private static final
String METHOD_GET = "GET";

All other pieces of theory are ok when you look at Public abstract class GenericServlet which implements servlet, servletconfig, serializable. wich the idea is to have a class in the future that don't necessarily need to implements all interface methods like httpservlet does.

Than you very much, I also would appreciate clearer or deeper resources of java class modeling.

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract.

yeah i misunderstood and misread the httservlet the rule only applies to abstract methods with no body just the signature but httpsevlet methods are not abstract they have implementation but is compiled =) thank you very much i see why now we don't need to implement those methods and the interfaces used by httpservlet.

1条回答
倾城 Initia
2楼-- · 2019-08-01 08:24

an abstract class may not implement methods ( but they can) and if you extend from an >abstract class you must implement all methods of superclass otherwise the new class must be >abstract as well

I think you've misread.

An abstract class does implement methods, you just don't get to use those methods until you extend the abstract Class into a concrete Class. Usually this is done because the methods in the abstract Class will be reused in various extending Classes. Some reasons for this are removing duplication, and hiding boiler plate code.

In the HttpServlet you get default implementations of the methods you described. You Override the ones you select when you want to extend the behavior of HttpServlet to suit your specific needs.

查看更多
登录 后发表回答