java - How to define destructors? -
public class { double wage; a(double wage){ this.wage=wage; } }
//in code supposed define constructors destructors.
- what code defining destructor?
in java, there no destructors
can use method object#finalize() work around.
the java programming language not guarantee thread invoke finalize method given object. guaranteed, however, thread invokes finalize not holding user-visible synchronization locks when finalize invoked. if uncaught exception thrown finalize method, exception ignored , finalization of object terminates.
class book { @override public void finalize() { system.out.println("book instance getting destroyed"); } } class demo { public static void main(string[] args) { new book();//note, not referred variable system.gc();//gc, won't run such tiny object forced clean-up } }
output:
book instance getting destroyed
runs garbage collector. calling gc method suggests java virtual machine expend effort toward recycling unused objects in order make memory occupy available quick reuse. when control returns method call, java virtual machine has made best effort reclaim space discarded objects.
the call system.gc() equivalent call:
runtime.getruntime().gc()
called garbage collector on object when garbage collection determines there no more references object. subclass overrides finalize method dispose of system resources or perform other cleanup.