Command Palette

Search for a command to run...

Back to the lesson: Topic 5.1 — Inheritance with extends
Core Java · Example 2 of 3

The exact construction order

Field initializers run after the parent constructor finishes, but before the rest of this class's constructor body.

class Dog extends Animal makes Dog a kind of Animal: it gets Animal's fields and methods for free and can add its own. A class can extend only one class, and every class ultimately extends java.lang.Object.

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 Vehicle with fields brand and wheels and a method describe() that prints them. Create Car (4 wheels) and Bike (2 wheels) that extend it, each setting wheels in its constructor and adding one method of its own. Print a description of each.

02

Write a three-level hierarchy Person → Employee → Manager where each constructor prints its name, and show the order they print in.

03

Print the full superclass chain of java.util.ArrayList using getSuperclass() in a loop.

Explain it without notes

01

What does extends give a subclass, and what does it not give?

02

Why does Java allow only one superclass?

03

In what order do constructors and field initializers run for new C() where C extends B extends A?

04

A Dog object can't name Animal's private name field. Does the Dog object still contain that field? Explain.

The exact construction order
Sign in to run this example in your browser.

Expected output

1. LivingThing constructor body
2. Animal field initializer
3. Animal constructor body
4. Dog field initializer
5. Dog constructor body