instanceof keyword usage

后端 未结 8 2278
野性不改
野性不改 2021-02-14 10:44

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:12

    Usage of instanceof is discouraged when same effect can be achieved via virtual methods, like in example of thomson_matt. However, it's necessary to use instanceof in some circumstances. For example, when your code gets Object from external source, say, network or third-party API which returns Object, and you must decide what is the type of this Object and act appropriately.

    0 讨论(0)
  • 2021-02-14 11:16

    Generally speaking yes. It's best to keep all code that depends on being a specific class within that class, and using instanceof generally means that you've put some code outside that class.

    Look at this very simple example:

    public class Animal
    {
    }
    
    public class Dog extends Animal
    {
    }
    
    public class Cat extends Animal
    {
    }
    
    public class SomeOtherClass
    {
      public abstract String speak(Animal a)
      {
        String word = "";
    
        if (a instanceof Dog)
        {
          word = "woof";
        }
        else if (a instanceof Cat)
        {
          word = "miaow";
        }
    
        return word;
      }
    }
    

    Ideally, we'd like all of the behaviour that's specific to dogs to be contained in the Dog class, rather than spread around our program. We can change that by rewriting our program like this:

    public abstract class Animal
    {
      public String speak();
    }
    
    public class Dog extends Animal
    {
      public String speak()
      {
        return "woof";
      }
    }
    
    public class Cat extends Animal
    {
      public String speak()
      {
        return "miaow";
      }
    }
    
    public class SomeOtherClass
    {
      public String speak(Animal a)
      {
        return a.speak();
      }
    }
    

    We've specified that an Animal has to have a speak method. Now SomeOtherClass doesn't need to know the particular details of each type of animal - it can hand that off to the subclass of Animal.

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