← 返回课程: Java from scratch

Inheritance and polymorphism

视频即将上线

Many things in the world share characteristics: a dog, a cat and a parrot are animals; all have a name and all make a sound, although each a different one. Inheritance lets you express that relationship in code: a child class (subclass) inherits fields and methods from a parent class (superclass) and can add its own or change the inherited ones. The keyword is extends. It is used when there is an is-a relationship: a dog IS an animal. With it you avoid copying the same code into several classes.

extends, super and @Override

The subclass constructor must call the superclass constructor with super(...) as its first statement, because the inherited part has to be built first. An inherited method can be redefined in the subclass with the same signature; this is called overriding and is marked with the @Override annotation, which makes the compiler warn you if you get the name or parameters wrong. Inside the overridden method you can call the parent's version with super.method(). Do not confuse overriding (same signature in a subclass) with overloading (same name, other parameters).

java
public class Main {
    public static void main(String[] args) {
        Animal generic = new Animal("Thing");
        Dog dog = new Dog("Rex");
        Cat cat = new Cat("Misu");

        generic.speak();      // Thing makes a sound
        dog.speak();          // Rex says Woof
        dog.fetch();          // Rex fetches the ball
        cat.speak();          // Misu says Meow and purrs
        System.out.println(dog.getName());   // inherited method: Rex
    }
}

class Animal {
    private final String name;

    Animal(String name) { this.name = name; }

    String getName() { return name; }

    void speak() {
        System.out.println(name + " makes a sound");
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);                     // must be the first line
    }

    @Override
    void speak() {
        System.out.println(getName() + " says Woof");
    }

    void fetch() {                       // only dogs have this
        System.out.println(getName() + " fetches the ball");
    }
}

class Cat extends Animal {
    Cat(String name) { super(name); }

    @Override
    void speak() {
        super.speak();                   // run the parent's version first
        System.out.println(getName() + " says Meow and purrs");
    }
}

Polymorphism

Here comes the powerful part. Since a Dog is an Animal, you can store a Dog in a variable of type Animal. If you walk through a list of Animal and call speak() on each one, Java runs in each case the version of the object's real class, not the variable's. This is called polymorphism (many forms) or dynamic binding. Your code can work with the general type and each object behaves according to its concrete type. If tomorrow you add the Parrot class, the loop will keep working without changes.

java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Animal> zoo = new ArrayList<>();
        zoo.add(new Dog("Rex"));
        zoo.add(new Cat("Misu"));
        zoo.add(new Animal("Thing"));

        for (Animal a : zoo) {
            a.speak();                   // each object uses its own version
        }

        Animal pet = new Dog("Luna");    // upcast: automatic and safe
        pet.speak();                     // Luna says Woof
        // pet.fetch();                  // error: Animal does not have fetch()

        if (pet instanceof Dog d) {      // check + downcast in one step
            d.fetch();                   // Luna fetches the ball
        }

        Animal other = new Cat("Tom");
        System.out.println(other instanceof Dog);   // false
        System.out.println(other.toString().startsWith("Cat@")); // default toString
    }
}

class Animal {
    private final String name;
    Animal(String name) { this.name = name; }
    String getName() { return name; }
    void speak() { System.out.println(name + " makes a sound"); }
}

class Dog extends Animal {
    Dog(String name) { super(name); }
    @Override void speak() { System.out.println(getName() + " says Woof"); }
    void fetch() { System.out.println(getName() + " fetches the ball"); }
}

class Cat extends Animal {
    Cat(String name) { super(name); }
    @Override void speak() { System.out.println(getName() + " says Meow"); }
}
  • Every class inherits from Object, which is why all objects have toString, equals and hashCode.
  • Java allows only single inheritance: a class extends one parent class. To combine capabilities you use interfaces (next lesson).
  • A final method cannot be overridden and a final class cannot be extended (String is final).
  • The private fields of the parent are not accessible from the child; use getters or protected.
  • The upcast (from Dog to Animal) is automatic; the downcast (from Animal to Dog) requires a check with instanceof or it will cause ClassCastException.
  • Sealed classes (Java 17) let you decide which classes may extend a given class.

检验所学

第 1 / 1

Which keyword is used to inherit?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →