Skip to content

OCP exam prep: constructors

☕ Java 17 · 🎓 OCP 1Z0-829 · Building Objects the Right Way with Constructors

Optional page

This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.

Exam objective: Create classes and records, and define and use constructors.

Four traps to watch for

Trap 1 — A return type means it's a method

A "constructor" with any return type, even void, is a regular method.

Trap 2 — Default only if none

Declaring any constructor removes the default no-argument one.

Trap 3 — First, once, not both

this(…) or super(…) must be the first statement, appear once, never both. No cycles, no var parameters.

Trap 4 — A parent that needs arguments

If the parent has no no-argument constructor, each child constructor must call super(…) or this(…); the hidden super() matches nothing.

Practice questions

1. Which child classes compile?

class Content { Content(String t) { } }
class Movie extends Content { }
class Series extends Content { Series() { } }
class Episode extends Content { Episode() { super("E1"); } }

A. Movie and Series
B. Episode only
C. Series and Episode
D. All three

Answer

B. Movie and Series both get a hidden super(), and Content has no no-argument constructor. Episode calls super(String).

2. Which line fails to compile?

1: class Trailer {
2:     Trailer() { this(30); }
3:     Trailer(int s) { System.out.print("init");
4:         this(s, true); }
5:     Trailer(int s, boolean hd) { seconds = s; }
6:     int seconds; }

A. Line 2
B. Line 4
C. Lines 2 and 4
D. It compiles

Answer

B. this(s, true) comes after a print statement. Line 2's this(30) is first, and matches Trailer(int).

3. What is printed by new Movie();?

class Content { Content() { System.out.print("C"); } }
class Movie extends Content {
    Movie() { this("M"); System.out.print("1"); }
    Movie(String s) { System.out.print(s); }
}

A. M1
B. CM1
C. 1MC
D. MC1

Answer

B. Movie() calls Movie(String), whose hidden super() prints C first. Then M, then back in Movie(), 1.

← Back to the series · All 1Z0-829 pages