为什么在servlet中使用public修饰符
我想要一些信息来准备第一个 servlet 程序。
谁能告诉我为什么我们在 servlet 以及 init()
、service()
和 destroy()
中将用户定义的类声明为 public > 也作为公众。
我们可以使用其他访问修饰符吗?那么它们是哪些呢?为什么只使用公共修饰符?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我们必须将 servlet 类以及 init、service 和 destroy 方法声明为公共,因为服务器应该能够访问这些方法。这与使用访问修饰符 public 声明的 main 方法非常相似。
另一个原因是在
HttpServlet
和GenericServlet
类中,这三个方法是公共的,您无法在继承的类中降低其访问级别。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 inGenericServlet
classes, these three methods are public whose access level you can not reduce in inherited classes.他们也可以得到保护。看看
HttpServlet
- 所有这些方法都在那里受到保护。 Servlet 的入口点是service(..)
方法 - 它是唯一可能需要公开的方法(但我不知道这样的要求 - 容器可以调用带反射的服务方法)They can be protected as well. Look at
HttpServlet
- all these methods are protected there. The entry-point to the servlet is theservice(..)
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)