instanceof keyword usage

后端 未结 8 2418
死守一世寂寞
死守一世寂寞 2021-02-14 10:21

Is using the instanceof keyword against the essence of object oriented programming? I mean is it a bad programming practice? I read somewhere that us

相关标签:
8条回答
  • 2021-02-14 11:09

    There are many good answers promoting virtual methods, but instanceof has its uses as well. Imagine that you iterate over List<Event>, to pick up all Urgent objects. You might do it using isUrgent() but I am not sure if it were necessarily more concise or readable. Also, isUrgent() would require making Event aware that its subclasses may possess the respective property, which might:

  • be regarded as something against modularity principles;
  • be even impossible, if Event belongs to some library that can not be modified.
0 讨论(0)
  • 2021-02-14 11:17

    It's discouraged because people might use it to do something like this:

    if( myAnimal instanceof Dog )
        ((Dog)myAnimal).bark();
    else( myAnimal instanceof Cat )
        ((Cat)myAnimal).meow();
    

    Instead, Animal should have a speak() method which Dog and Cat inherit. In proper OOP with polymorphism and dynamic binding, you would then simply do

    myAnimal.speak();
    

    However, there are some instances in which you must use instanceof to determine the specific type of an object. Perhaps you have a list of Animals in your house and the only ones you want to take out for a walk() are the Dogs. In that case you would iterate through your list and only walk() the dogs.

    0 讨论(0)
  • 提交回复
    热议问题