Skip to content

OCP exam prep: overriding and hiding

☕ Java 17 · 🎓 OCP 1Z0-829 · Rewriting What Your Parent Class Does

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: Implement polymorphism and differentiate object type versus reference type.

Four traps to watch for

Trap 1 — Overload ≠ override

Same name, different parameters: an overload. None of the override rules apply.

Trap 2 — Static mismatch

One method static, the other not: doesn't compile. Both static: hiding. Neither: overriding.

Trap 3 — Who decides?

Fields and static methods: the variable's type. Overridden instance methods: the real object.

Trap 4 — private versus final

Private methods can be redeclared freely. Final methods can't be overridden or hidden.

Practice questions

1. Which lines fail to compile? (java.io.* is imported.)

1: class Content { public void play() { }
2:     protected Object info() { return "c"; }
3:     void load() throws IOException { } }
4: class Movie extends Content { void play() { }
5:     public String info() { return "m"; }
6:     void load() throws Exception { } }

A. Line 4 only
B. Lines 4 and 6
C. Lines 5 and 6
D. Lines 4, 5 and 6

Answer

B. Line 4 narrows public to package access. Line 6 declares a broader checked exception. Line 5 is fine: wider access and a covariant return type.

2. With Content x = new Movie();, what does x.label + x.kind() + x.type() give?

class Content { String label = "content";
    static String kind() { return "C"; }
    String type() { return "c"; } }
class Movie extends Content { String label = "movie";
    static String kind() { return "M"; }
    String type() { return "m"; } }

A. contentCm
B. movieMm
C. contentMm
D. movieCm

Answer

A. The field and the static method are hidden, so the variable's type (Content) decides: content, C. type() is overridden, so the real object (Movie) decides: m.

3. Which methods of Episode compile?

class Media { public final void play() { }
    public static void stop() { }
    private final void rate() { } }
class Episode extends Media { public void play() { }
    public void stop() { }
    private void rate() { } }

A. play() only
B. rate() only
C. stop() and rate()
D. All three

Answer

B. play() is final. stop() mixes static and instance. rate() is private in Media, so not inherited: Episode declares a new method.

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