Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

java - When should and shouldn't instanceof be used?

I have gone through various articles, but I still do not know why instanceof should not be used. Kindly let me know your thoughts.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I find a need to use instanceof hints at bad design. It's a sure sign that a big, complex switch-style construct will follow. Most other times I see it used, we should use polymorphism rather than instanceof. See the Strategy pattern. (relevant examples of use)

The only time I find I need to use it is when implementing equals(Object o).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...