Command Palette

Search for a command to run...

Back to the lesson: Topic 5.3 — Method Overriding and @Override
Core Java · Example 2 of 4

Overload picked at compile time, override at run time

FancyPrinter didn't override print(String), so the inherited Printer version runs for the second call.

Overriding means a subclass gives its own version of an inherited instance method with the same name and parameters. @Override asks the compiler to check that you really are overriding, which catches typos and wrong signatures.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create Shape with String name() returning "shape" and Square overriding it with @Override. Then add a method name(String prefix) in Square. Print which ones are overrides and which is an overload by calling them.

02

Write Document with Document copy(), and Invoice extends Document with a covariant Invoice copy(). Show that invoice.copy() needs no cast.

03

Write a correct equals(Object) and hashCode() for Point(int x, int y) and show list.contains and set.size() behave correctly.

Explain it without notes

01

List the rules an overriding method must follow.

02

What's the difference between overloading and overriding, in terms of when the decision is made?

03

Why does public boolean equals(Point p) break HashSet and ArrayList.contains?

04

What is a bridge method and why does javac create one for a covariant return?

Overload picked at compile time, override at run time
Sign in to run this example in your browser.

Expected output

FancyPrinter.print(Object)
Printer.print(String)
FancyPrinter.print(Object)