问题
I want some info to prepare the first servlet program.
Can anyone let me know that why we declare the userdefined class as public in servlet as well as init()
, service()
and destroy()
also as public.
Can we use other access modifiers then which are they? Why to use only public modifiers?
回答1:
We have to declare servlet class and the methods init, service and destroy as public because the server should be able to access these. This is very similar to the main method declaring with the access modifier public.
Another reason is in HttpServlet
and in GenericServlet
classes, these three methods are public whose access level you can not reduce in inherited classes.
回答2:
They can be protected as well. Look at HttpServlet
- all these methods are protected there. The entry-point to the servlet is the service(..)
method - it is the only one that is potentially required to be public (but I don't know of such requirement - the container can invoke the service method with reflection)
来源:https://stackoverflow.com/questions/9117331/why-to-use-public-modifier-in-servlet