☰ 总览更新 10-12 22:33

11 · 多态

我的原话

一句话:编译看左边,运行看右边

Animal x = new Cat();
x.call();
时候 谁 看哪边 做什么
编译 编译器 左边 Animal 只查有没有 call → 有,放行
运行 JVM 右边(仓库里实际的对象) 是猫 → 执行猫的 call → 喵喵

编译器只问「能不能叫」,运行时才定「叫出谁的声」。

捡球

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