How does one use polymorphism instead of instanceof? (And why?)(如何使用多态性而不是 instanceof?(为什么?))
问题描述
If we take the code below:
Shape p1 = new Square();
Square c1;
if(p1 instanceof Square) {
c1 = (Square) p1;
}
What does it mean to prefer polymorphism to instanceof
, and incidentally, why is it better?
Edit: I understand what polymorphism is; what I'm missing is how one would use it rather than instanceof
.
The main difference between if...else... (or switch, or Visitor), and between polymorphism is modularity. There's so called open-closed principle, which basically means, that when you add a new feature to an existing program, the less changes you make in existing code the better (because every change requires some work, and may introduce bugs). So let's compare the amount of changes:
adding a new method (eg. you have paint(), and getArea(), let's add getCircumference()): with if-else solution you only have to alter just one file - the file which will contain the new method. With polymorphism, you have to alter all your implementations of Shape class.
adding a new kind of Shape (you have Square, Circle - let's add Triangle): with if-else solution you have to review all existing classes with if-else and add a new if branch for Triangle; with polymporphism all you have is to add a new class and implement all required methods in it.
So if...else... or polymorphism: it depends on modularity. If you expect that many new sublasses will be added later, use polymorphism; if you expect that many new methods will be added later, use if...else..., and in the class put only the most "basic" methods like accessors. Or in other words: when you expect to have many if...else... branches, you should rather use polymorphism, when you expect few such branches, just stay with if...else...
Additionally: when you expect few if...else... branches, but in lots of places, you should consider encapsulating this if...else... with Visitor pattern or just making an enum with a separate case for each branch.
这篇关于如何使用多态性而不是 instanceof?(为什么?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用多态性而不是 instanceof?(为什么?)


基础教程推荐
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01