instanceof关键字用法

instanceof关键字用法

本文介绍了instanceof关键字用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 instanceof 关键字来反对面向对象编程的本质
我的意思是这是一个糟糕的编程习惯吗?
我在某处读到使用 instanceof 关键字意味着设计可能不那么好。有没有更好的解决方法?

Is using the instanceof keyword against the essence of object oriented programming?I mean is it a bad programming practice?I read somewhere that using instanceof keyword means that the design may not be that good. Any better workaround?

推荐答案

一般来说是的。最好保留所有依赖于该类中特定类的代码,并且使用 instanceof 通常意味着您已经在该类之外放置了一些代码。

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;
  }
}

理想情况下,我们喜欢所有的行为特定于Dog类中包含的狗,而不是在我们的程序中传播。我们可以通过改写我们的程序来改变它:

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();
  }
}

我们已经指定 Animal 必须有一个发言方法。现在 SomeOtherClass 不需要知道每种动物的特定细节 - 它可以将其移交给 Animal

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.

这篇关于instanceof关键字用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:35