Animal x = new Cat();
x.call();
| 时候 | 谁 | 看哪边 | 做什么 |
|---|---|---|---|
| 编译 | 编译器 | 左边 Animal | 只查有没有 call → 有,放行 |
| 运行 | JVM | 右边(仓库里实际的对象) | 是猫 → 执行猫的 call → 喵喵 |
编译器只问「能不能叫」,运行时才定「叫出谁的声」。
Animal a = new Dog(); a.fetch(); → 编译错「找不到符号」:Animal 没有 fetchDog d = new Dog(); d.fetch(); ✅ 当狗看,能捡球static void makeNoise(Animal x) { x.call(); } // 前台:什么动物都收
makeNoise(new Dog()); // 汪汪
makeNoise(new Cat()); // 喵喵
| 题 | 我答 | 结果 |
|---|---|---|
Animal x = new Cat(); x.call() 打印? |
Animal 的 call | ❌ 喵喵:运行看右边 |
| 编译检查谁 | Animal | ✅ |
| Dog 重写了 call、Cat 没写:p.call() q.call() | 汪汪、(动物叫) | ✅ |
真跑过:T20、T21.java