Core Java

core11Inheritance

Path
pkg1core/core11Inheritance.java
Package
pkg1core
Study order
12
Run
Single-file source launch
Command
java pkg1core/core11Inheritance.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core11Inheritance.java
1package pkg1core;2 3/*4 * core11Inheritance.java5 * ----------------6 * Reusing and extending behavior with `extends`, `super`, and constructors.7 *8 * EXPLANATION:9 *  - A subclass inherits accessible fields/methods of its superclass.10 *  - `super(...)` calls the parent constructor; `super.m()` calls the parent method.11 *  - Constructors run parent-first (Object -> ... -> subclass).12 *  - Favor composition over inheritance when "is-a" doesn't truly hold.13 */14public class core11Inheritance {15 16    static class Animal {17        protected String name;18        Animal(String name) { this.name = name; }19        String sound() { return "..."; }20        void describe() { System.out.println(name + " says " + sound()); }21    }22 23    static class Dog extends Animal {24        Dog(String name) { super(name); }          // call parent constructor25        @Override String sound() { return "Woof"; } // override behavior26    }27 28    static class Puppy extends Dog {29        Puppy(String name) { super(name); }30        @Override String sound() {31            return super.sound() + " (tiny)";       // extend parent behavior32        }33    }34 35    public static void main(String[] args) {36        new Animal("Generic").describe();37        new Dog("Rex").describe();38        new Puppy("Bit").describe();39 40        // Subclass IS-A superclass41        Animal a = new Dog("Fido");42        System.out.println("Dog is Animal? " + (a instanceof Animal));43        System.out.println("a.sound() dispatches to Dog: " + a.sound());44    }45}