java - How does one use polymorphism instead of instanceof? (And why?) -


if take code below:

shape p1 = new square(); square c1; if(p1 instanceof square) {   c1 = (square) p1; } 

what mean prefer polymorphism instanceof, , incidentally, why better?

edit: understand polymorphism is; i'm missing how 1 use rather instanceof.

the main difference between if...else... (or switch, or visitor), , between polymorphism modularity. there's called open-closed principle, means, when add new feature existing program, less changes make in existing code better (because every change requires work, , may introduce bugs). let's compare amount of changes:

  • adding new method (eg. have paint(), , getarea(), let's add getcircumference()): if-else solution have alter 1 file - file contain new method. polymorphism, have alter implementations of shape class.

  • adding new kind of shape (you have square, circle - let's add triangle): if-else solution have review existing classes if-else , add new if branch triangle; polymporphism have add new class , implement required methods in it.

so if...else... or polymorphism: depends on modularity. if expect many new sublasses added later, use polymorphism; if expect many new methods added later, use if...else..., , in class put "basic" methods accessors. or in other words: when expect have many if...else... branches, should rather use polymorphism, when expect few such branches, stay if...else...

additionally: when expect few if...else... branches, in lots of places, should consider encapsulating if...else... visitor pattern or making enum separate case each branch.


Comments

Popular posts from this blog

SAP Web Service from .NET via WCF -

Optimized Line drawing in QT -

datetime - str to time in python -