Lesson content
Read, practise, then check your understanding
A constructor has the class name and no return type. It initializes a new object after superclass construction and field initialization. this(...) delegates within the class; super(...) delegates to the direct superclass, and either must be first.
Construction and cleanup
final class Report implements AutoCloseable {
private final BufferedWriter writer;
Report(Path path) throws IOException {
writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
}
void write(String line) throws IOException { writer.write(line); }
@Override public void close() throws IOException { writer.close(); }
}
try (Report report = new Report(path)) {
report.write("ready");
}
Java has no deterministic destructor. Garbage collection reclaims unreachable memory but does not promise timely release of files, sockets, locks, or native handles. Use AutoCloseable and try-with-resources. Finalization is deprecated/removed from modern practice; Cleaner is only a defensive fallback. Do not let this escape during construction, and prefer immutable successfully constructed objects.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.