Question

For example:

/**
 * Constructor
 */
public Test(InputStream in){
   try{
      this.inputStream = in;
   } finally{
      inputStream.close();
   }
}

Is the InputStream that is passed to the instructor immediately closed after the Test object is created? Or is it closed when the Test object is destroyed? I don't know how to implement something similar to a destructor in C++.

Was it helpful?

Solution

It's executed as part of a constructor. The code executed within a constructor is just normal code - there's no odd control flow there. (I mean after the call to the superclass constructor, and the variable/instance initializers being run.)

There's no equivalent to a C++ destructor in Java. The closest you'll get is a finalizer, but that should not be used as the equivalent of a C++ destructor. (You should hardly ever write finalizers. There are cases where they're not called on shutdown, and they're called non-deterministically.)

In the case you've given, you would probably not want your class to assume responsibility for closing the input stream - usually the code which opens the stream is responsible for closing it as well. However, if you did want to take responsibility for that, or just make it easier for callers, you would probably want to expose a close() method which just closes the stream. You might want to implement AutoCloseable too, so that callers can use a try-with-resources statement with your class:

try (Test test = new Test(new FileInputStream("foo.txt")) {
    // Do stuff with test
}

That will call test.close() automatically at the end of the try block.

OTHER TIPS

Finally will be immediately executed after try. It does not matter it is in constructor. It is well defined in JLS.

It says:

A try statement with a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then the finally block is executed, and then there is a choice:
    • If the finally block completes normally, then the try statement
      completes normally.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top