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.
Closeable
, and callingclose()
on the underlying inputStream there: docs.oracle.com/javase/7/docs/api/java/io/Closeable.html – Adjunct