如何定义析构函数?

时间:2015-04-23 04:59:32

标签: java oop destructor

    public class A {

    double wage;

    A(double wage){
    this.wage=wage;
    }

    }

//在这段代码中,我应该定义构造函数和析构函数。

  • 定义析构函数的代码是什么?

2 个答案:

答案 0 :(得分:7)

In Java, there are no destructors but you can use method Object#finalize() as a work around.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

class Book {
  @Override
  public void finalize() {
    System.out.println("Book instance is getting destroyed");
  }
}

class Demo {
  public static void main(String[] args) {
    new Book();//note, its not referred by variable
    System.gc();//gc, won't run for such tiny object so forced clean-up
  }
}

output:

Book instance is getting destroyed

System.gc()

Runs the garbage collector. Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

Object#finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

答案 1 :(得分:2)

Write your own method and use it. It is not recommended to override finalize method.