为什么我们使用 init() 而不是构造函数 [英] Why we use init() rather Constructor

查看:38
本文介绍了为什么我们使用 init() 而不是构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要 init() 而不是 constructor?

why do we need init() rather than a constructor?

请参考ServletApplet.
Appletinit()Servlet 有何不同?

Please answer in reference of Servlet and Applet.
How does the init() of Applet differ from Servlet?

推荐答案

init() 方法创建并加载 servlet.但是servlet实例首先是通过构造函数创建的(由Servlet容器完成).我们不能在 servlet 中编写带有参数的 servlet 类的构造函数(它会抛出异常).因此,他们提供了一个 init() 方法,该方法接受一个 ServletConfig 对象作为参数.ServletConfig 对象为 servlet 提供有关其初始化 (init) 参数的信息.Servlet 类不能声明以 ServletConfig 对象为参数的构造函数,也不能访问 ServletConfig 对象.

The init() method creates and loads the servlet. But the servlet instance is first created through the constructor (done by Servlet container). We cannot write constructors of a servlet class with arguments in servlet (It will throw Exception). So, They provided a init() method that accepts an ServletConfig object as an argument. ServletConfig object supplies a servlet with information about its initialization (init) parameters. Servlet class cannot declare a constructor with ServletConfig object as a argument and cannot access ServletConfig object.

更多信息位于:http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html

这篇关于为什么我们使用 init() 而不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆