多态本身不直接提升扩展性,它只是让扩展变得安全、可控、无需修改旧代码;通过interface+多态将行为抽象为方法签名,新增子类只需实现接口,调用方代码不变,编译器可检查实现完整性。
多态本身不直接提升扩展性,它只是让「扩展变得安全、可控、无需修改旧代码」——前提是设计得当。
if-else 分支就要动已有类?常见反模式:用类型判断硬编码行为
if (obj instanceof Dog) {
((Dog) obj).bark();
} else
if (obj instanceof Cat) {
((Cat) obj).meow();
}
这种写法一旦新增 Bird 类,就必须打开原有逻辑、加新分支、重新编译测试。违反开闭原则。
instanceof 的地方补漏Bird 处理)interface + 多态把变化点「抽成方法签名」把行为抽象为接口方法,让每个子类自己决定怎么实现:
interface Animal {
void makeSound(); // 统一入口,具体由子类实现
}
class Dog implements Animal { public void makeSound() { System.out.println("Woof"); } }
class Cat implements Animal { public void makeSound() { System.out.println("Meow"); } }
此时新增 Bird 只需:
Bird 类并实现 Animal
animal.makeSound() 自动路由到新实现关键不是“能调用”,而是「新增行为不污染已有模块」。
abstract class 有时比 interface 更适合扩展?当多个子类共享部分实现(比如通用字段、模板方法),abstract class 能避免重复代码,同时保留多态能力:
abstract class Vehicle {
protected String brand;
public Vehicle(String brand) { this.brand = brand; }
public abstract void start(); // 子类必须实现
public void printBrand() { System.out.println(brand); } // 共享逻辑
}
新增 ElectricCar 时,可复用 printBrand(),只重写 start();而如果全用 interface,就得在每个实现类里重复写品牌打印逻辑。
default 方法,但无法持有状态(字段)abstract class 是更自然的选择interface 可能导致“空接口堆砌”,反而增加理解成本多态不是写了 extends 或 implements 就自动生效的:
static 方法不参与多态:调用的是声明类型上的静态方法,不是运行时类型animal.name 取的是 Animal 类定义的字段,不是子类重定义的NullPointerException 或默认值误用这些地方看似用了继承,实际绕过了动态绑定机制,扩展时极易出错且难以调试。