×

java · level 2 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A a and gets everything it has.

Dogs and cats are both animals: each has a name and can eat. Write those once, in Animal, then write static class Dog extends Animal. Dog is the subclass, and Animal is its superclass. Dog inherits every field and method, then adds its own.

A subclass constructor must let the superclass fill in its fields first. calls the Animal constructor, and it must be the very first line. After that, the subclass sets up its own extras.

public class Main {
    static class Animal {
        String name;
        Animal(String name) {
            this.name = name;
        }
        String eat() { return name + " is eating."; }
    }
    static class Dog extends Animal {
        Dog(String name) {
            super(name);
        }
        String fetch() { return name + " fetches the ball!"; }
    }
    public static void main(String[] args) {
        Dog rex = new Dog("Rex");
        System.out.println(rex.eat());
        System.out.println(rex.fetch());
    }
}

Read extends as is a kind of: a dog is a kind of animal.