In Java when is the final block in a constructor executed?
Asked Answered
G

2

8

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++.

Gey answered 31/10, 2013 at 7:10 Comment(3)
Related: Is there a destructor for Java?Hatching
The existing answers are sufficient, but also consider making your class implement Closeable, and calling close() on the underlying inputStream there: docs.oracle.com/javase/7/docs/api/java/io/Closeable.htmlAdjunct
@CoryKendall thanks I think I'd better implement Closeable for my case.Gey
L
11

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.

Lerma answered 31/10, 2013 at 7:12 Comment(0)
T
2

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.
Tonita answered 31/10, 2013 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.