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.
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.
Write a three-level hierarchy Person → Employee → Manager where each constructor prints its name, and show the order they print in.
Print the full superclass chain of java.util.ArrayList using getSuperclass() in a loop.
Explain it without notes
What does extends give a subclass, and what does it not give?
Why does Java allow only one superclass?
In what order do constructors and field initializers run for new C() where C extends B extends A?
A Dog object can't name Animal's private name field. Does the Dog object still contain that field? Explain.
Expected output
Dog
Animal
java.lang.Object
d instanceof Animal: true
d instanceof Object: true
toString from Object: true