How do I define destructors?

    public class A {

    double wage;

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

    }

      

// In this code, I have to define constructors as well as destructors.

  • What is the code for defining a destructor?
+3


source to share


2 answers


Java does no destructors

, but you can use Object # finalize () method as work.

The Java programming language does not guarantee which thread will invoke the finalize method on any given object. It is guaranteed, however, that the thread that calls the termination will not have user-dependent synchronization locks when finalize is called. If a thrown exception is thrown by the finalize method, the exception is ignored and the completion of this object ends.

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. The call to gc shows that the Java Virtual Machine is spending effort recycling unused objects in order to make the memory they currently occupy reuse. When control returns from a method call, the Java Virtual Machine has made every effort to free up space from any discarded objects.

Calling System.gc () is actually equivalent to calling:

Runtime.getRuntime (). Ds ()

# Finalize () object

Called by the garbage collector on an object during garbage collection, determines that there are no more references to the object. The subclass overrides the finalization method to utilize system resources or perform other cleanup.

+5


source


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



+1


source







All Articles