java中的生命周期方法

时间:2012-10-09 10:42:59

标签: java

当一个类继承这个类并覆盖这些生命周期方法时,如何使用某些以某种顺序执行的方法(即类的生命周期方法)创建一个类?

例如:

  1. 在Servlet中,首先调用init()然后调用service(),最后在创建servlet对象时自动调用destroy()。

  2. android中的活动有生命周期方法onCreate(),onStart(),onResume()等,当活动对象出现时自动调用

4 个答案:

答案 0 :(得分:1)

JAVA的生命周期方法

由于applet在浏览器中运行,因此Applet类包含生命周期方法。 生命周期方法也称为环回方法。

在java.applet.Applet中,我们有四个生命周期方法。他们是

public void init (),
public void start (),
public void stop () 
public void destroy ().

<强> 1。 Public void init():

This is the method which is called by the browser only one time after loading the applet.
In this method we write some block of statements which will perform one time operations, such as, obtaining the resources like opening the files, obtaining the database connection, initializing the parameters, etc.

<强> 2。 Public void start():

  After calling the init method, the next method which is from second request to sub-sequent requests the start method only will be called i.e., short method will be called each and every time.
In this method we write the block of statement which provides business logic.

第3。公共void stop():

  This id the method which is called by the browser when we minimize the window. 
In this method we write the block of statements which will temporarily releases the resources which are obtained in init method.

<强> 4。 Public void destroy():

This is the method which will be called by the browser when we close the window button or when we terminate the applet application.
In this method we write same block of statements which will releases the resources permanently which are obtained in init method.

另一种不是生命周期方法的方法是public void paint()。这是方法 完成start方法后,浏览器将调用它。该方法用于显示 浏览器上的数据。 Paint方法在内部调用名为drawString的方法 原型如下。 java.awt.Graphics (Graphics =&gt; public void drawString(String,int row position,int column position)) 将applet加载到之后,将自动创建Graphics类的对象 浏览器。

答案 1 :(得分:0)

这些方法的排序由引用您的类的框架/容器强制执行。我通常希望您的框架要求客户端实现特定的接口(包含start()stop()等),框架本身将确定状态机和后续行为。

答案 2 :(得分:0)

您需要应用程序容器(最简单的解释是它是某个类,它将按指定的顺序执行类的指定方法)。但是你需要更深入地理解应用程序容器的概念。我建议你阅读Spring

答案 3 :(得分:0)

最简单的是,您可以使用模板方法方法满足您的要求:

public class Template {
  public void templateMethod() {
    detail1();
    detail2();
  }
  protected void detail1() {}
  protected void detail2() {}

}

然后你继承Template类。