Skip to content

OCP exam prep: this and super

☕ Java 17 · 🎓 OCP 1Z0-829 · Building Child Classes with this and super

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.

Four traps to watch for

Trap 1 — private is never accessible to the child

A child naming a parent's private field doesn't compile, even deep inside a long method. Read every line.

Trap 2 — Top level: public or nothing

private or protected on a top-level class fails. Several package-access classes in one file are fine.

Trap 3 — The backwards assignment

x = this.x; compiles but changes nothing in the field. Expect 0, null or the initial value.

Trap 4 — super sees only the parent

super.x fails if x exists only in the child; this.x sees both. Neither works in static code.

Practice questions

1. Which statement is true?

class Content { protected String genre = "Drama"; }

public class Movie extends Content {
    int year = 2024;
    void showGenre() { System.out.print(this.genre + super.genre); }
    void showYear()  { System.out.print(this.year + super.year); }
}

A. It compiles
B. Only showGenre() fails
C. Only showYear() fails
D. Both fail

Answer

C. year exists only in Movie, and super never looks in the current class. genre is inherited, so both this.genre and super.genre work.

2. What is the output?

public class User {
    private String name = "guest";
    void rename(String name) { name = this.name; }

    public static void main(String[] args) {
        var u = new User();
        u.rename("Mounir");
        System.out.print(u.name);
    }
}

A. Mounir
B. guest
C. null
D. It doesn't compile

Answer

B. name = this.name copies the field into the parameter: the field still holds guest. It compiles: main reads u.name through an object, inside User, so private is fine.

3. Each option alone is the top-level class of Episode.java. Which compile? (Choose two.)

A. public class Episode { }
B. protected class Episode { }
C. class Season { }
D. private class Trailer { }

Answer

A and C. A is public and named like the file. C has package access, so its name doesn't have to match. protected and private aren't allowed on a top-level class.

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