Command Palette

Search for a command to run...

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

Walk up the tree to Object

Object's toString() prints the class name, '@', and a hex hash code, so we only check the prefix to keep the output stable.

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.

Walk up the tree to Object
Sign in to run this example in your browser.

Expected output

Dog
Animal
java.lang.Object
d instanceof Animal: true
d instanceof Object: true
toString from Object: true