多态:一种类型,多种行为
- 多态(polymorphism)的意思是"多种形态":一个父类类型,多种子类行为。
- 你可以把一个
Dog或一个Cat放进一个Animal变量里,因为它们各自是一种Animal。 - 当你调用一个方法时,由对象的真实类型决定运行哪个版本。
动态分派
- 变量的类型(
Animal)决定你被允许调用哪些方法。 - 但在运行时,由实际的对象(
Dog)决定运行哪个被重写的版本。 - 这种运行时的选择叫作动态分派(dynamic dispatch) —— 它是多态的核心。
public class Main {
public static void main(String[] args) {
Animal[] zoo = { new Dog(), new Cat(), new Dog() };
for (Animal a : zoo) {
System.out.println(a.speak()); // Woof, then Meow, then Woof
}
}
}
class Animal {
public String speak() { return "some sound"; }
}
class Dog extends Animal {
public String speak() { return "Woof"; }
}
class Cat extends Animal {
public String speak() { return "Meow"; }
}
一个循环处理所有子类
- 上面的循环从不问"这是 Dog 还是 Cat?" —— 它只是调用
speak()。 - 每个对象用自己的方式回答。这让循环保持简短而通用。
- 以后再加一个全新的子类,同一个循环不用改就能处理它。
toString():每个对象都从 Object 继承它
- Java 里每个类其实都暗中继承自一个叫
Object的类,它有一个toString()。 - 重写
toString(),来说明你的对象作为文本时应该长什么样。 - 当你打印一个对象,或用
+拼接它时,Java 会自动调用它。
public class Main {
public static void main(String[] args) {
Object x = new Fraction(3, 4);
System.out.println(x); // 3/4 -- toString() runs
System.out.println("ratio " + x); // ratio 3/4
}
}
class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
}
常见错误
- 运行时调用的是实际对象的方法(动态分派),而非变量的类型。
- 重写
toString()以得到可读的输出。
现在轮到你
- 用一个父类数组、加一个新子类,再重写
toString()。 - 一个隐藏的 Harness(检查程序)会检查每个对象运行的是正确的版本。
- 使用 检查答案 将代码与提供的测试用例一同编译并查看结果。请保留引导代码中显示的类和方法接口。您的代码将在服务器上编译和运行。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Animal, Dog, and Cat are written for you. Complete the static method Zoo.chorus(Animal[] animals) so it returns every animal's sound joined by single spaces. Example: a Dog, Cat, Dog array gives "Woof Meow Woof". An empty array gives "". Loop and call speak() — let polymorphism pick the right sound.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Animal, Dog, Cat, and a working Zoo.chorus are written for you. Add a class Cow that extends Animal and overrides speak() to return "Moo". Notice the existing chorus loop handles your new Cow with no changes.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Complete Fraction by overriding toString() so it returns the fraction as "numerator/denominator" — for 3 and 4 it returns "3/4". Java calls toString() automatically when you print a Fraction or join it with +.
点击“运行”查看此处输出。