Skip to content

Chapter 10 of 37

Constructors and Object Lifecycle

Initialize objects, delegate constructors, and manage resources without destructors.

36 minutes 10 quick checksBy Subha Prasad
Lesson 10 of 37Course navigation

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.

Which statement best describes constructor?
Which Java term matches this description: A special declaration that initializes a newly allocated object.
Which statement best describes this constructor call?
Which Java term matches this description: Delegation to another constructor in the same class.
Which statement best describes super constructor call?
Which Java term matches this description: Initialization of the direct superclass portion.
Which statement best describes try-with-resources?
Which Java term matches this description: Deterministic closing of AutoCloseable resources.
Which statement best describes Cleaner?
Which Java term matches this description: A last-resort cleanup mechanism that is not a deterministic destructor.

0 of 10 checks passed

Your progress is saved on this device.